File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Statement Exceution Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Statement Exceution" Watch "Statement Exceution" New topic

Statement Exceution

Lakshmi Saradha
Ranch Hand

Joined: Oct 21, 2003
Posts: 170
I found this question in one of the forums. The ans is 2 .
How is line 1 executed ? I understand that the method getarray() is called and then assignment takes place, but looks a bit vague to me
Is there a place in the internet where I can learn abt execution of such statememts.?

class Test
public static int[ ] getArray() { return null; }
public static void main(String[] args)
int index = 1;
getArray()[index=2]++; //line 1
catch (Exception e){ } //empty catch
System.out.println("index = " + index);

Thanks,<br />Lakshmi.
Lakshmi Saradha
Ranch Hand

Joined: Oct 21, 2003
Posts: 170
Is there anyone who can help me with this?
Vad Fogel
Ranch Hand

Joined: Aug 25, 2003
Posts: 504
We've got a sequence of 3 postfix operators of the equal priority here:
postfix operators [] (params) expr++
The evaluation flows left to right. First, a call to getArray() gets resolved returning null. Second, index is assigned 2 for the array, and third - the postfix increment is supposed to occur, but it never does because of NullPointerException being thrown.
Here's a modified code to demonstrate that evaluation indeed occurs left to right:

The result is:
index = 1
You can see that index was not assigned 2 since getArray() blew up with an exception. Refer to Operators Precedence and to the Dan's exams to clear the concept.
I agree. Here's the link:
subject: Statement Exceution
It's not a secret anymore!