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.
+
- addition
-
- subtraction
*
- multiplication
/
- division
%
- remainder
Arithmetic operators applied to two int
s return an int
. The result will be truncated and may over- or underflow.
Arithmetic operators applied to two double
s return a double
.
Arithmetic operators applied to an int
and a double
return a double
.
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
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)
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.
(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
rangeInteger.MAX_VALUE
⟹ 2,147,483,647 (a.k.a 2^31 - 1)
Integer.MIN_VALUE
⟹ -2,147,483,648 (a.k.a. -2^31)
Arithmetic on int
s 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
Dividing by zero with int
s results in an ArithmeticException
.
Dividing by zero with double
s results in the special value Double.POSITIVE_INFINITY
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.