Java Reference
In-Depth Information
Sample Run:
5.0 + 3.5 = 8.5
3.0 + 9.4 = 12.4
16.4 - 5.2 = 11.2
4.2 * 2.5 = 10.5
5.0 / 2.0 = 2.5
34.5 / 6.0 = 5.75
34.5 % 6.0 = 4.5
34.5 / 6.5 = 5.3076923076923075
34.5 % 6.5 = 2.0
2
Order of Precedence
When more than one arithmetic operator is used in an expression, Java uses the operator
precedence rules to determine the order in which the operations are performed to evaluate
the expression. According to the order of precedence rules for arithmetic operators:
*, /, %
have a higher level of precedence than:
+,
-
Note that the operators * , / , and % have the same level of precedence. Similarly, the
operators + and - have the same level of precedence.
When arithmetic operators have the same level of precedence, operations are performed
from left to right. To avoid confusion, you can use parentheses to group arithmetic
expressions.
EXAMPLE 2-4
Using the order of precedence rules,
3 * 7 - 6 + 2 * 5 / 4 + 6
means the following:
(((3 * 7) - 6) + ((2 * 5) / 4 )) + 6
= ((21 - 6) + (10 / 4)) + 6 (Evaluate * )
= ((21 - 6) + 2) + 6 (Evaluate / . Note that this is an integer division.)
= (15 + 2) + 6 (Evaluate - )
= 17 + 6 (Evaluate first + )
= 23 (Evaluate + )
Note that using parentheses in the preceding expression clarifies the order of precedence.
 
Search WWH ::




Custom Search