10.12.2012 Views

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

EXPRESSIONS Evaluate Left-Hand Operand First 15.7.1<br />

It is recommended that code not rely crucially on this specification. Code is<br />

usually clearer when each expression contains at most one side effect, as its<br />

outermost operation, and when code does not depend on exactly which exception<br />

arises as a consequence of the left-to-right evaluation of expressions.<br />

15.7.1 Evaluate Left-Hand Operand First<br />

<strong>The</strong> left-hand operand of a binary operator appears to be fully evaluated before<br />

any part of the right-hand operand is evaluated. For example, if the left-hand operand<br />

contains an assignment to a variable and the right-hand operand contains a<br />

reference to that same variable, then the value produced by the reference will<br />

reflect the fact that the assignment occurred first.<br />

Thus:<br />

class Test {<br />

public static void main(String[] args) {<br />

int i = 2;<br />

int j = (i=3) * i;<br />

System.out.println(j);<br />

}<br />

}<br />

prints:<br />

9<br />

It is not permitted for it to print 6 instead of 9.<br />

If the operator is a compound-assignment operator (§15.26.2), then evaluation<br />

of the left-hand operand includes both remembering the variable that the left-hand<br />

operand denotes and fetching and saving that variable’s value for use in the<br />

implied combining operation. So, for example, the test program:<br />

class Test {<br />

public static void main(String[] args) {<br />

int a = 9;<br />

a += (a = 3); // first example<br />

System.out.println(a);<br />

int b = 9;<br />

b = b + (b = 3); // second example<br />

System.out.println(b);<br />

}<br />

}<br />

prints:<br />

12<br />

12<br />

because the two assignment statements both fetch and remember the value of the<br />

left-hand operand, which is 9, before the right-hand operand of the addition is<br />

DRAFT<br />

415

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!