Java Reference
In-Depth Information
2
+
3 * 4
2
3*4
5
* 4
2+
12
20
14
The first of these evaluates to 20 while the second evaluates to 14 . To deal with the
ambiguity, Java has rules of precedence that determine how to group together the var-
ious parts.
Precedence
The binding power of an operator, which determines how to group parts of
an expression.
The computer applies rules of precedence when the grouping of operators in
an expression is ambiguous. An operator with high precedence is evaluated first,
followed by operators of lower precedence. Within a given level of precedence the
operators are evaluated in one direction, usually left to right.
For arithmetic expressions, there are two levels of precedence. The multiplicative
operators ( * , / , % ) have a higher level of precedence than the additive operators
( + , - ). Thus, the expression 2 + 3 * 4 is interpreted as
2
+
3 * 4
2 +
12
14
Within the same level of precedence, arithmetic operators are evaluated from left
to right. This often doesn't make a difference in the final result, but occasionally it
does. Consider, for example, the expression
40 - 25 - 9
which evaluates as follows:
40
-
25 - 9
15
- 9
6
You would get a different result if the second subtraction were evaluated first.
You can always override precedence with parentheses. For example, if you really
want the second subtraction to be evaluated first, you can force that to happen by
introducing parentheses:
40 - (25 - 9)
 
Search WWH ::




Custom Search