Hi, I came across this question: -------------------------------------- int i = 0; int[] a = {3,6}; a[i] = i = 9; // line 3 System.out.println(i + " " + a[0] + " " + a[1]); Select the one right answer: a) Raises ArrayIndexOutOfBoundsException b) Prints "9 9 6" c) Prints "9 0 6" d) Prints "9 3 6" e) Prints "9 3 9" I would like to know why the answer is b) not a) ? Thank you. Rgds.
M Huang
Greenhorn
Joined: Jun 18, 2003
Posts: 9
posted
0
I'm not sure. It looks confusing. I do know that the [] operator has higher precedence than the = operator. So it's probably because expression a[i] gets evaluated first, locking in the fact that you will store whatever it is into a[0]. And then i gets 9, and a[0] gets 9. OK, now that I've thought about it for a bit, drew a parse tree, and thought about some other examples (int x = 3*3 + 4 is the simplest that comes to mind), I am absolutely sure that that's the correct explanation. How tricky! Where did you get such a tricky question? [ June 18, 2003: Message edited by: M Huang ]
Barkat Mardhani
Ranch Hand
Joined: Aug 05, 2002
Posts: 787
posted
0
Here is how I look at: int i = 0; int[] a = {3,6}; a[i] = i = 9; // line 3 System.out.println(i + " " + a[0] + " " + a[1]); 1. First assignment (=) takes precedence over second assignment (=) .... left to right rule 2. a[i] = i as i = 0 a[0] = 0 3. Now second assignment: i = 9 4. So println will give: 9 0 6 Hope this makes sense... Thanks Barkat
SCJP1.4
"Continuous effort - not strength or intelligence - is the key to unlocking our potential."
*Winston Churchill
Damien Howard
Ranch Hand
Joined: Apr 01, 2003
Posts: 456
posted
0
but according to Dominic the answer was b not c or a. So can someone explain this? [ June 18, 2003: Message edited by: Damien Howard ]
Veena Pointi
Ranch Hand
Joined: Jun 20, 2002
Posts: 442
posted
0
Originally posted by Damien Howard: but according to Dominic the answer was b not c or a. So can someone explain this? [ June 18, 2003: Message edited by: Damien Howard ]
Assignment is from right to left not left to right What does assignment do "replace" i= 9 a[0] = 9 and a[1] = 6 B right? [ June 18, 2003: Message edited by: James Chegwidden ]
Mr. C<br /> <br />Author and Instructor<br />My book:<br /><a href="http://www.aw-bc.com/catalog/academic/product/0,1144,1576761614,00.html" target="_blank" rel="nofollow">http://www.aw-bc.com/catalog/academic/product/0,1144,1576761614,00.html</a>
Dominic Choo
Greenhorn
Joined: Jan 30, 2003
Posts: 26
posted
0
I get this question from Khalid's Book. It's really tricky.
Brian Joseph
Ranch Hand
Joined: May 16, 2003
Posts: 160
posted
0
Read the thread from the link above. Marlene describes how to evaluate the = expression. You need to take the expression through a few passes. First identify where the parenetheses go, then evaluate left to right.