View on GitHub

Notes

reference notes

Manipulating Numbers

In Java, to add two numbers x and y, we write x + y. But before the actual addition of the two numbers takes place, we must declare their data type. If x and y are integers, we write:

int x, y;

or

int x;
int y;

Variables

Numerical Data Types

There are six numerical data types: byte, short, int, long, float, and double.

Sample variable declarations:

int i, j, k;
float numberOne, numberTwo;
long bigInteger;
double bigNumber;

At the time a variable is declared, it can also be initialized. For example, we may initialize the integer variables count and height to 10 and 34 as:

int count = 10, height = 34;

Data Type Precisions

The six data types differ in the precision of values they can store in memory.

Higher precision

Assignment Statements

Having Two References to a Single Object

Invalid Declarations

Arithmetic Operators

The following table summarizes the arithmetic operators available in Java:

Operation Operator Example Value (x = 10, y = 7, z = 2.5)
Addition + x + y 17
Subtraction - x - y 3
Multiplication * x * y 70
Division / x / y 1
Modulus % x % y 3

Arithmetic Expression

Here are the remaining notes organized using Markdown:

Precedence Rules

Order Group Operators Rule
1 Subexpression ( ) Evaluate expressions within parentheses first.
2 Unary + - ++ – ! Evaluate unary operators next.
3 Multiplicative * / % Evaluate multiplicative operators next.
4 Additive + - Evaluate additive operators next.

Type Casting

Explicit Type Casting

Implicit Type Casting

Constants

Displaying Numerical Values

int num = 15;
System.out.print(num); //print a variable
System.out.print(" "); //print a string
System.out.print(10); //print a constant

Output:

15 10

Overloaded Operator +

The DecimalFormat Class

Getting Numerical Input

Methods

Method Example
nextByte() byte b = scanner.nextByte();
nextDouble() double d = scanner.nextDouble();
nextFloat() float f = scanner.nextFloat();
nextInt() int i = scanner.nextInt();
nextLong() long l = scanner.nextLong();
nextShort() short s = scanner.nextShort();
nextLine() String str = scanner.nextLine();

Sample Program

import java.util.*;
import java.text.*;

class Ch3Circle4 {
  public static void main(String[] args) {
    final double PI = 3.14159;
    final String TAB = "\t";
    final String NEWLINE = "\n";
    double radius, area, circumference;
    Scanner scanner = new Scanner(System.in);
    DecimalFormat df = new DecimalFormat("0.000");
    
    // Get input
    System.out.print("Enter radius: ");
    radius = scanner.nextDouble();
    
    // Compute area and circumference
    area = PI * radius * radius;
    circumference = 2.0 * PI * radius;
    
    // Display the results
    System.out.println(
      "Given Radius: " + TAB + df.format(radius) + NEWLINE +
      "Area: " + TAB + df.format(area) + NEWLINE +
      "Circumference: " + TAB + df.format(circumference)
    );
  }
}

Output (when user enters 12 as the radius):

Enter radius: 12
Given Radius: 12.000
Area: 452.389
Circumference: 75.398

The Math class

The Math class in the java.lang package contains class methods for commonly used mathematical functions.

Some Math Class Methods

Method Description
exp(a) Natural number e raised to the power of a.
log(a) Natural logarithm (base e) of a.
floor(a) The largest whole number less than or equal to a.
max(a,b) The larger of a and b.
pow(a,b) The number a raised to the power of b.
sqrt(a) The square root of a.
sin(a) The sine of a. (Note: all trigonometric functions are computed in radians)

Table 3.7 on page 113 in the textbook contains a list of class methods defined in the Math class.

Computing the Height of a Pole

alphaRad = Math.toRadians(alpha);
betaRad = Math.toRadians(beta);
height = (distance * Math.sin(alphaRad) * Math.sin(betaRad)) /
         Math.sqrt(Math.sin(alphaRad + betaRad) * Math.sin(alphaRad - betaRad));

Random Number Generation

import java.util.*;
...
Random random = new Random( );
int num = random.nextInt( );
int num = random.nextInt(11); // Generates a random integer between 0 and 10
int num = random.nextInt(6) + 1;
int num = random.nextInt(max - min + 1) + min;

The GregorianCalendar Class

GregorianCalendar today, independenceDay;
today = new GregorianCalendar();
independenceDay = new GregorianCalendar(1776, 6, 4); // month 6 means July; 0 means January

Retrieving Calendar Information

Constant Description
YEAR the year portion of the date
MONTH the month portion of the date
DATE the day of the month
DAY_OF_MONTH the day of the month
DAY_OF_WEEK the day of the week
DAY_OF_YEAR the day of the year
HOUR the hour portion of the time
MINUTE the minute portion of the time
SECOND the second portion of the time
MILLISECOND the millisecond portion of the time

Sample Calendar Retrieval

GregorianCalendar cal = new GregorianCalendar();
// Assume today is Dec 18, 2008
System.out.print("Today is " +
  (cal.get(Calendar.MONTH) + 1) + "/" +
  cal.get(Calendar.DATE) + "/" +
  cal.get(Calendar.YEAR));

Output:

Today is 12/18/2008