• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Reg Arrays

 
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This a question from one of the mock exams.
Please go through the code...

What will be the result of compiling and running the given program?
Select one correct answer.

1. class Q55
2. {
3. public static void main(String[] args)
4. {
5. int[] a={11,12,13,14};
6. int[] b={0,1,2,3};
7. System.out.println(a[(a=b)[3]]);
8. }
9. }
1. Compile time error at line number 7.
2. Runtime error at line number 7.
3. Program will compile correctly and print 3 when executed.
4. Program will compile correctly and print 14 when executed.
The answer given is 4.
Can any one explain me how 14 is the output.

Thanks in advance.
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is a tricky question, and it's hard to explain how it works.

When evaluating a[(a=b)[3]] the assignment to a (that is, the a=b) does not affect the dereferencing of the outer array (the outermost a[]). The expression is being evaluated in the same way as a[b[3]] would be.

It's a good idea to inspect the output of the "javap -c -l -verbose Q55" command . You can see how the stack machine evaluator is processing that statement.

You will not see a question as tricky as that on the SCJP 1.4 examination.
[ October 22, 2004: Message edited by: Barry Gaunt ]
 
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Barry,

Thanks for such a great use of javap.exe.

But I am facing a problem in windows me, that is, I can not see the whole output of the command given by you in your reply.

Do you know any such tool, which can show the whole output???

Thanks
Kaps
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Kaps, you should be able to do "javap -c -l -verbose Q55 > somefile.txt"

The you can read the file with your favourite text editor.

Or you can "pipe" it into more:
"javap -c -l -verbose Q55 | more"
 
reply
    Bookmark Topic Watch Topic
  • New Topic