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.

15.26.2 Compound Assignment Operators EXPRESSIONS<br />

524<br />

null[throw]+=12345 => IndexThrow<br />

null[9]+=throw => NullPointerException<br />

null[9]+=throw => NullPointerException<br />

null[9]+="heh" => NullPointerException<br />

null[9]+=12345 => NullPointerException<br />

Strings[throw]+=throw => IndexThrow<br />

doubles[throw]+=throw => IndexThrow<br />

Strings[throw]+="heh" => IndexThrow<br />

doubles[throw]+=12345 => IndexThrow<br />

Strings[1]+=throw => RightHandSideThrow<br />

doubles[1]+=throw => RightHandSideThrow<br />

Strings[1]+="heh" => Okay!<br />

doubles[1]+=12345 => Okay!<br />

Strings[throw]+=throw => IndexThrow<br />

doubles[throw]+=throw => IndexThrow<br />

Strings[throw]+="heh" => IndexThrow<br />

doubles[throw]+=12345 => IndexThrow<br />

Strings[9]+=throw => ArrayIndexOutOfBoundsException<br />

doubles[9]+=throw => ArrayIndexOutOfBoundsException<br />

Strings[9]+="heh" => ArrayIndexOutOfBoundsException<br />

doubles[9]+=12345 => ArrayIndexOutOfBoundsException<br />

<strong>The</strong> most interesting cases of the lot are tenth and eleventh from the end:<br />

Strings[1]+=throw => RightHandSideThrow<br />

doubles[1]+=throw => RightHandSideThrow<br />

<strong>The</strong>y are the cases where a right-hand side that throws an exception actually gets<br />

to throw the exception; moreover, they are the only such cases in the lot. This<br />

demonstrates that the evaluation of the right-hand operand indeed occurs after the<br />

checks for a null array reference value and an out-of-bounds index value.<br />

<strong>The</strong> following program illustrates the fact that the value of the left-hand side<br />

of a compound assignment is saved before the right-hand side is evaluated:<br />

class Test {<br />

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

int k = 1;<br />

int[] a = { 1 };<br />

k += (k = 4) * (k + 2);<br />

a[0] += (a[0] = 4) * (a[0] + 2);<br />

System.out.println("k==" + k + " and a[0]==" + a[0]);<br />

}<br />

}<br />

This program prints:<br />

k==25 and a[0]==25<br />

<strong>The</strong> value 1 of k is saved by the compound assignment operator += before its<br />

right-hand operand (k = 4) * (k + 2) is evaluated. Evaluation of this right-hand<br />

DRAFT

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

Saved successfully!

Ooh no, something went wrong!