Java Reference
In-Depth Information
parentheses, the operators are applied according to the precedence rule and the associativity
rule.
The precedence rule defines precedence for operators, as shown in Table 3.10, which
contains the operators you have learned so far. Operators are listed in decreasing order of
precedence from top to bottom. The logical operators have lower precedence than the
relational operators and the relational operators have lower precedence than the arithmetic
operators. Operators with the same precedence appear in the same group. (See Appendix C,
Operator Precedence Chart , for a complete list of Java operators and their precedence.)
operator precedence
T ABLE 3.10
Operator Precedence Chart
Precedence
Operator
var++ and var-- (Postfix)
+ , - (Unary plus and minus), ++var and --var (Prefix)
(type) (Casting)
! (Not)
* , / , % (Multiplication, division, and remainder)
+ , - (Binary addition and subtraction)
< , <= , > , >= (Comparison)
== , != (Equality)
^ (Exclusive OR)
&& (AND)
|| (OR)
= , += , -= , *= , /= , %= (Assignment operator)
If operators with the same precedence are next to each other, their associativity deter-
mines the order of evaluation. All binary operators except assignment operators are left asso-
ciative . For example, since + and - are of the same precedence and are left associative, the
expression
operator associativity
is equivalent to
a - b + c - d
((a - b) + c) - d
Assignment operators are right associative . Therefore, the expression
is equivalent to
a = b += c = 5
a = (b += (c = 5))
Suppose a , b , and c are 1 before the assignment; after the whole expression is evaluated, a
becomes 6 , b becomes 6 , and c becomes 5 . Note that left associativity for the assignment
operator would not make sense.
Note
Java has its own way to evaluate an expression internally. The result of a Java evaluation
is the same as that of its corresponding arithmetic evaluation. Advanced readers may
refer to Supplement III.B for more discussions on how an expression is evaluated in Java
behind the scenes .
behind the scenes
 
Search WWH ::




Custom Search