Java Reference
In-Depth Information
2.8.4 Expression evaluation
The operands of an operator are always evaluated from left to right. For
example, in
x = a+b;
the + operator will determine the value of expression a and then expression b .
Do not get this rule confused with the precedence and associativity rules, dis-
cussed next.
Precedence determines the order in which operators act in an expression with
more than one operator. Table A.2.9 gives the precedence rating for each operator,
the higher number indicating higher precedence.
Associativity rules determine how the compiler groups the operands and oper-
ators in an expression with more than one operator of the same precedence. For
example, in the expression
x = a+b*c;
the evaluation begins with a and then the + operator determines its right
operand. But in this case the right operand consists of the expression b*c .
The multiplication operator * has a higher precedence than the additive oper-
ator + so b multiplies c rather than sums with a .
Precedence can be overridden with parentheses, as in
x = (a+b)*c;
The parentheses force the addition of b to a , and then c multiplies this sum.
Although the precedence ratings, which are similar to those in C/C
,were
chosen for the most “natural” ordering of the operator evaluations, it never hurts
to use the parentheses if you are unsure of the precedence and to make the code
more readable.
When the operations in an expression all have the same precedence rating, the
associativity rules determine the order of the operations. For most operators, the
evaluation is done from left to right, as in
++
x = a-b+c;
Here, addition and subtraction have the same precedence rating, so a and b are
subtracted and then c added to the difference. Again, parentheses can be used to
overrule the default associativity, as in
x = a-(b+c);
The assignment and unary operators, on the other hand, are associated right to
left. For example, the statement
x+ = y- = - ~ 4;
Search WWH ::




Custom Search