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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

15.13.2 Examples: Array Access Evaluation Order EXPRESSIONS<br />

484<br />

because the monstrous expression’s value is equivalent to a[b[3]] or a[3] or 14.<br />

If evaluation of the expression to the left of the brackets completes abruptly,<br />

no part of the expression within the brackets will appear to have been evaluated.<br />

Thus, the example:<br />

class Test {<br />

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

int index = 1;<br />

try {<br />

skedaddle()[index=2]++;<br />

} catch (Exception e) {<br />

System.out.println(e + ", index=" + index);<br />

}<br />

}<br />

static int[] skedaddle() throws Exception {<br />

throw new Exception("Ciao");<br />

}<br />

}<br />

prints:<br />

java.lang.Exception: Ciao, index=1<br />

because the embedded assignment of 2 to index never occurs.<br />

If the array reference expression produces null instead of a reference to an<br />

array, then a NullPointerException is thrown at run time, but only after all<br />

parts of the array access expression have been evaluated and only if these evaluations<br />

completed normally. Thus, the example:<br />

class Test {<br />

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

int index = 1;<br />

try {<br />

nada()[index=2]++;<br />

} catch (Exception e) {<br />

System.out.println(e + ", index=" + index);<br />

}<br />

}<br />

static int[] nada() { return null; }<br />

}<br />

prints:<br />

java.lang.NullPointerException, index=2<br />

because the embedded assignment of 2 to index occurs before the check for a null<br />

pointer. As a related example, the program:<br />

class Test {<br />

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

int[] a = null;<br />

try {<br />

DRAFT

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

Saved successfully!

Ooh no, something went wrong!