Java Reference
In-Depth Information
It is possible to get a result of 0 for the mod operator. This happens when one
number divides evenly into another. For example, each of the following expressions
evaluates to 0 because the second number goes evenly into the first number:
28 % 7
95 % 5
44 % 2
A few special cases are worth noting because they are not always immediately
obvious to novice programmers:
Numerator smaller than denominator: In this case division produces 0 and
mod produces the original number. For example, 7 / 10 is 0 and 7 % 10 is 7 .
Numerator of 0: In this case both division and mod return 0. For example, both
0 / 10 and 0 % 10 evaluate to 0 .
Denominator of 0: In this case, both division and mod are undefined and pro-
duce a runtime error. For example, a program that attempts to evaluate either 7 /
0 or 7 % 0 will throw an ArithmeticException error.
The mod operator has many useful applications in computer programs. Here are
just a few ideas:
Testing whether a number is even or odd ( number % 2 is 0 for evens, number %
2 is 1 for odds).
Finding individual digits of a number (e.g., number % 10 is the final digit).
Finding the last four digits of a social security number ( number % 10000 ).
The remainder operator can be used with double s as well as with integers, and it
works similarly: You consider how much is left over when you take away as many
“whole” values as you can. For example, the expression 10.2 % 2.4 evaluates to
0.6 because you can take away four 2.4 s from 10.2 , leaving you with 0.6 left over.
For floating-point values (values of type double ), the division operator does what
we consider “normal” division. So, even though the expression 119 / 5 evaluates to
23 , the expression 119.0 / 5.0 evaluates to 23.8 .
Precedence
Java expressions are like complex noun phrases in English. Such phrases are subject
to ambiguity. For example, consider the phrase “the man on the hill by the river with
the telescope.” Is the river by the hill or by the man? Is the man holding the tele-
scope, or is the telescope on the hill, or is the telescope in the river? We don't know
how to group the various parts together.
You can get the same kind of ambiguity if parentheses aren't used to group the
parts of a Java expression. For example, the expression 2 + 3 * 4 has two opera-
tors. Which operation is performed first? You could interpret this two ways:
 
Search WWH ::




Custom Search