Win a copy of Secure Financial Transactions with Ansible, Terraform, and OpenSCAP this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Rob Spoor
  • Henry Wong
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh
  • Jj Roberts

Statement Exceution

 
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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;
try
{
getArray()[index=2]++; //line 1
}
catch (Exception e){ } //empty catch
System.out.println("index = " + index);
}
}
 
Lakshmi Saradha
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is there anyone who can help me with this?
 
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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:
java.lang.ArithmeticException
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 know this defies the law of gravity... but I never studied law." -B. Bunny Defiant tiny ad:
SKIP - a book about connecting industrious people with elderly land owners
https://coderanch.com/t/skip-book
reply
    Bookmark Topic Watch Topic
  • New Topic