Java Reference
In-Depth Information
Parentheses are used just as in algebra: to indicate in which order the subexpressions
should be computed. For example, in the expression (a + b) / 2 , the sum a +
b is computed first, and then the sum is divided by 2. In contrast, in the expression
a + b / 2
only b is divided by 2, and then the sum of a and b / 2 is formed. Just as in regular
algebraic notation, multiplication and division bind more strongly than addition and
subtraction. For example, in the expression a + b / 2 , the / is carried out first,
even though the + operation occurs farther to the left.
Division works as you would expect, as long as at least one of the numbers involved
is a floating-point number. That is,
If both arguments of the / operator are integers, the result is an integer and the
remainder is discarded.
7.0 / 4.0
7 / 4.0
7.0 / 4
148
149
all yield 1.75. However, if both numbers are integers, then the result of the division is
always an integer, with the remainder discarded. That is,
7 / 4
evaluates to 1, because 7 divided by 4 is 1 with a remainder of 3 (which is discarded).
This can be a source of subtle programming errorsȌsee Common Error 4.1 .
If you are interested only in the remainder of an integer division, use the % operator:
The % operator computes the remainder of a division.
7 % 4
is 3, the remainder of the integer division of 7 by 4. The % symbol has no analog in
algebra. It was chosen because it looks similar to /, and the remainder operation is
related to division.
Search WWH ::




Custom Search