• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

doubt in multiple assignment !

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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

------------------
 
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic