How does the assignment occur
Submitted by Annu on Fri, 09/19/2008 - 20:19.
Hi,
Can you please tell me how does this piece of code work
int a[] = new int[4];
void aMethod()
{
int b = 0 , index;
a[a[b]] = a[b] = b = 2;
index = ??? ;
System.out.println(a[index]);
}
What value assigned to the variable index will print a non zero result?
Thanks in advance
Annu
Annu,
Before I can answer your question, we require that you indicate where your question was obtained from(as indicated in the forum posting guidelines) - http://www.irixtech.com/content/forum-posting-guidelines-0
Since some mock exams give out real exam questions, we like to make sure that we're not discussing real exam questions. Doing so is a copyright violation & for any exam takers it would amount to cheating.
Thanks
Ashish Hareet
Hi,
I obtained the above question when I was solving the mock paper from the following site.
http://www.javablackbelt.com/QuestionnaireDefDisplay.wwa?questPublicId=0...
And this link I got it from http://faq.javaranch.com/java/ScjpMockTests.
Thanks and regards
Annu
Thanks for providing the reference, I'm at work right now, expect an answer sometime in the next 10 hrs or so.
Ashish Hareet
Since int a[] is a member variable it'll get inititalized to the default values, so
a[0] = 0
a[1] = 0
a[2] = 0
a[3] = 0
Now referring to JLS 15.2.6.1 -in particular note the 2nd bulleted point, here's how we can evaluate a[a[b]] = a[b] = b = 2;
Finally what we're left with is b = 2 and a[0] = 2, which means that index has to be 0, cause that was the only index that got set as a result of the assignment.
HTH
Ashish Hareet