• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in multiple assignment !

 
kusumac
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class test{
public static void main(String args[])
{
int i=0;
int[] a={3,4};
a[i]=i=9;
System.out.println(i+" "+a[i]);
}
}
A) Raises ArrayIndexOutOfBoundException
B) Prints "9 9 6"
C) Prints "9 0 6"
D) Prints "9 3 6"
E) Prints "9 3 9"
In the Mughal Book(p 74), hesays the answer is B, but i think( also checked it) the answer is A.
am i correct ot not? clarify me.
thanks in advance
 
REVATHI GANESH
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
class test{
public static void main(String args[])
{
int i=0;
int[] a={3,4};
a[i]=i=9;
System.out.println(i+" "+a[i]);
}
}
Your answer is correct it happens this way:
take the expression:
a[i]=i=9

first, expressions inside brackets () , [] are evaluated.
Step1:
a[i] becomes a[0].
Then assignment takes place right to left.

1.i is assigned 9.
2.a[0] (from step 1) is assigned i's value- it is 9.

now take the System.out.println statement:
In this a[i] will be a[9] which will throw arrayindexoutofbound exception.
Hope this helps
Revathi

------------------
 
Bharatesh H Kakamari
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right. The answer is A.
In line :
a[i]=i=9;
[] has got higher precedence. Hence a[0] is evaluated first. Then 9 is assigned to i (because = is evaluated from R to L. This value 9 is then assigned to a[0];
S.o.p a[i] tries to print a[9] hence throws the exception.
HTH
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic