|
|
Operators and Assignments - Arithmetic Operators
Additive operators (JLS §15.18)
- + and -
- have the same precedence and are left-associative
- operands must be primitive numeric types (see exception for String and +) or compile error occurs
Multiplicative operators (JLS §15.17)
- *, /, %
- have the same precedence and are left-associative
- operands must be primitive numeric types or compile error occurs;
Integer Division and Division by Zero (JJ pg 50, JLS §15.17.2)
10.34 / 0 // result: Infinity
-10.34 / 0 // result: -Infinity
10.34 / -0 // result: Infinity
0 / 0 // result: NaN (Not a number)
Modulo operations (JLS §15.17.3)
- the modulo operator % is also called the remainder operator as it returns the remainder, or fractional part, of a division operation
- x % y is equivalent to x - ((int) (x/y) * y)
- can be used with both integer and floating-point numbers
- following rules apply as to the sign of the result:
- result is negative if the divdend is negative
- result is positive if the divdend is positive
- if the divisor is zero, a runtime
ArithmeticException is thrown
- if the dividend is a floating-point value and the divisor is zero, no exception is thrown and the result is NaN
5 % 3 = 2
-5 % 3 = -2
5.0 % 3 = 2.0
-5.0 % 3 = -2.0
5.0 % 0 = NaN // not a number
Also see:
Example Code
Traps
- floating point operation throwing an ArithmeticException
|