This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt in multiple assignment ! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "doubt in multiple assignment !" Watch "doubt in multiple assignment !" New topic
Author

doubt in multiple assignment !

kusumac
Greenhorn

Joined: Nov 22, 2000
Posts: 4
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

Joined: Jul 29, 2000
Posts: 4
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

Joined: Nov 09, 2000
Posts: 198
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: doubt in multiple assignment !