Numbers review

Numeric data types

int - 32-bit integer values

double - 64-bit floating point values with fractional parts.

These are two of the three primitive types we learned about.

Arithmetic operators

+ - addition

- - subtraction

* - multiplication

/ - division

% - remainder

Doubles are zombies

Arithmetic operators applied to two ints return an int. The result will be truncated and may over- or underflow.

Arithmetic operators applied to two doubles return a double.

Arithmetic operators applied to an int and a double return a double.

Casting

The cast operator (int) and (double) operates on a single numeric value and converts it to the given type.

(int) 3.14 ⟹ 3

(double) 10 ⟹ 10.0

Casting a double to an int truncates the value, chopping off the fractional part. It does not round to the nearest integer.

(int) 1.99999 ⟹ 1

Rounding

The College Board wants you to know you can round a double d like:

(int) (d + 0.5) // for positive d
(int) (d - 0.5) // for negative d

In the real world you’d probably do

(int) Math.round(d)

Order of operations

Arithmetic operators and parentheses have basically normal PEMDAS precedence.

Between operators with the same precedence (+ and - and also * and /) operators are evaluated from left to right.

The cast operator is higher precedence than all the arithmetic operators but below parenthesis.

Examples

(int) Math.random() * 10 ⟹ 0
(int) (Math.random() * 10) ⟹ 0 to 9 (inclusive)
(double) 3 / 4 ⟹ 0.75
(double) (3 / 4) ⟹ 0.0
3 / 4 * 1.0 ⟹ 0.0
1.0 * 3 / 4 ⟹ 0.75

int range

Integer.MAX_VALUE ⟹ 2,147,483,647 (a.k.a 2^31 - 1)

Integer.MIN_VALUE ⟹ -2,147,483,648 (a.k.a. -2^31)

Overflow and underflow

Arithmetic on ints wraps around.

Integer.MAX_VALUE + 1 ⟹ Integer.MIN_VALUE
Integer.MAX_VALUE + 2 ⟹ Integer.MIN_VALUE + 1
Integer.MAX_VALUE * 2 ⟹ Integer.MIN_VALUE +
                         Integer.MAX_VALUE - 1
Integer.MAX_VALUE * 2 ⟹ -2
Integer.MIN_VALUE - 1 ⟹ Integer.MAX_VALUE

Division by zero

Dividing by zero with ints results in an ArithmeticException.

Dividing by zero with doubles results in the special value Double.POSITIVE_INFINITY

Assignment operators

Normal assignent is just =, e.g. x = 10.

Numeric variables can be assigned with compound assignment operators.

x += 10   // equivalent to x = x + 10
x -= 23   // equivalent to x = x - 23
x *= 2    // equivalent to x = x * 2
x /= 10.0 // equivalent to x = x / 10.0
x %= 3    // equivalent to x = x % 3

Also x++ and x-- to increment and decrement by one.