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.

EXPRESSIONS Runtime Evaluation of Method Invocation 15.12.4<br />

15.12.4.6 Example: Target Reference and Static Methods<br />

When a target reference is computed and then discarded because the invocation<br />

mode is static, the reference is not examined to see whether it is null:<br />

class Test {<br />

static void mountain() {<br />

System.out.println("Monadnock");<br />

}<br />

static Test favorite(){<br />

System.out.print("Mount ");<br />

return null;<br />

}<br />

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

favorite().mountain();<br />

}<br />

}<br />

which prints:<br />

Mount Monadnock<br />

Here favorite returns null, yet no NullPointerException is thrown.<br />

15.12.4.7 Example: Evaluation Order<br />

As part of an instance method invocation (§15.12), there is an expression that<br />

denotes the object to be invoked. This expression appears to be fully evaluated<br />

before any part of any argument expression to the method invocation is evaluated.<br />

So, for example, in:<br />

class Test {<br />

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

String s = "one";<br />

if (s.startsWith(s = "two"))<br />

System.out.println("oops");<br />

}<br />

}<br />

the occurrence of s before “.startsWith” is evaluated first, before the argument<br />

expression s="two". <strong>The</strong>refore, a reference to the string "one" is remembered as<br />

the target reference before the local variable s is changed to refer to the string<br />

"two". As a result, the startsWith method is invoked for target object "one"<br />

with argument "two", so the result of the invocation is false, as the string "one"<br />

does not start with "two". It follows that the test program does not print “oops”.<br />

DRAFT<br />

479

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

Saved successfully!

Ooh no, something went wrong!