3.8. Operand Evaluation Order

 
[Page 86 ( continued )]

3.7. Operator Precedence and Associativity

Operator precedence and associativity determine the order in which operators are evaluated. Suppose that you have this expression:

   3   +   4   *   4   >   5   * (   4   +   3   )   1   

What is its value? How does the compiler know the execution order of the operators? The expression in the parentheses is evaluated first. (Parentheses can be nested, in which case the expression in the inner parentheses is executed first.) When evaluating an expression without 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. 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.)

Table 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)

& (Unconditional AND)

^ (Exclusive OR)

(Unconditional OR)

&& (Conditional AND)

(Conditional OR)

= , += , “= , *= , /= , %= (Assignment operator)


If operators with the same precedence are next to each other, their associativity determines the order of evaluation. All binary operators except assignment operators are left-associative . For example, since + and - are of the same precedence and are left-associative, the expression


[Page 87]

Assignment operators are right-associative . Therefore, the expression

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.

Applying the operator precedence and associativity rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows :

Tip

You can use parentheses to force an evaluation order as well as to make a program easy to read. Use of redundant parentheses does not slow down the execution of the expression.


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net