• 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

Reference variables and wrappers

 
Ranch Hand
Posts: 686
Netbeans IDE Chrome Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
These questions are taken from SCJP 5 quiz by Mark Dechamps (Inquisition). I am unable to understand the answers. Can someone help me? I was thinking the answer is 6 but correct answer is 5.



A. 6
B. 5
C. Exception is thrown at runtime
D. Doesn't compile
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
a post increment operator is used here.so the answer is 5.
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Can someone help me? I was thinking the answer is 6 but correct answer is 5.



You have to remember that Integer objects are not mutable. So, for the increment to work, the value needs to be unboxed, incremented, and boxed again. The unboxing and boxing, changes the object that y references. It is no longer referencing the same object as x.

The x reference is still referring to the previous object -- which has the value of 5.

Henry
 
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Integer x=5;
Integer y=x;
y++;

Code after compilation would look something like this.

Integer x = Integer.valueOf(5);
Integer y = Integer.valueOf(5);
y = Integer.valueOf(y.intValue()+1);

So as you can see, y points to a different object after the increment.
 
reply
    Bookmark Topic Watch Topic
  • New Topic