3.2 Evaluation Order of Operands


In order to understand the result returned by an operator, it is important to understand the evaluation order of its operands . Java states that the operands of operators are evaluated from left to right.

Java guarantees that all operands of an operator are fully evaluated before the operator is applied. The only exceptions are the short-circuit conditional operators && , , and ?: .

In the case of a binary operator, if the left-hand operand causes an exception (see Section 5.5, p. 181), the right-hand operand is not evaluated. The evaluation of the left-hand operand can have side effects that can influence the value of the right-hand operand. For example, in the following code:

 int b = 10; System.out.println((b=3) + b); 

the value printed will be 6 and not 13 . The evaluation proceeds as follows :


(b=3) + b
    3 + b b  is  assigned  the  value  3
    3 + 3
    6

The evaluation order also respects any parentheses, and the precedence and associativity rules of operators.

Examples illustrating how the operand evaluation order influences the result returned by an operator, can be found in Sections 3.4 and 3.7.



A Programmer[ap]s Guide to Java Certification
A Programmer[ap]s Guide to Java Certification
ISBN: 201596148
EAN: N/A
Year: 2003
Pages: 284

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