Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# Question on Precedence/Assignment

Dominic Choo
Greenhorn
Posts: 26
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]);
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
Posts: 9
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
Posts: 787
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

Veena Pointi
Ranch Hand
Posts: 442
I think following link discusses the same
http://www.coderanch.com/t/242181/java-programmer-SCJP/certification/Operator-precedence
veena

Damien Howard
Ranch Hand
Posts: 456
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
Posts: 442
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 ]

http://www.coderanch.com/t/242181/java-programmer-SCJP/certification/Operator-precedence

James Chegwidden
Author
Ranch Hand
Posts: 201
Let me try:

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 ]

Dominic Choo
Greenhorn
Posts: 26
I get this question from Khalid's Book.
It's really tricky.

Brian Joseph
Ranch Hand
Posts: 160
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.