3.4 Simple Arithmetic Expressions | 109
Programmers rarely use the unary plus. Without any sign, a numeric constant is assumed
to be positive anyway.
You may be less familiar with integer division and modulus (%), so let’s look at them
more closely. Note that %can be used with both integers and floating-point numbers. When
you divide one integer by another, you get an integer quotient and a remainder. Integer di-
vision gives only the integer quotient, and %gives only the remainder.
3 ←6 / 2 3 ←7 / 2
2)6 2)7
66
0 ←6 % 2 1 ←7 % 2
In Java, the sign of the remainder is the same as the sign of the dividend. For example:
3 % 2 = 1
3 % –2 = 1
–3 % 2 = –1
–3 % –2 = –1
In contrast to integer division, floating-point division yields a floating-point result. For
example, the expression
7.2 / 2.0
yields the value 3.6.
The floating-point remainder operation returns the remainder after dividing the dividend
by the divisor a whole number of times. For example,
7.2 % 2.1
yields the value 0.9 because 2.1 goes into 7.2 exactly 3 times (3 * 2.1 = 6.3), with 0.9 remaining.
Here are some expressions using arithmetic operators and their values:
Expression Value
3 + 6 9
3.4 – 6.1 2.7
2 * 3 6
8 / 2 4
8.0 / 2.0 4.0
8 / 8 1
8 / 9 0
8 / 7 1