• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reference variables and wrappers

 
Vyas Sanzgiri
Ranch Hand
Posts: 686
Chrome Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • 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
 
Sambit Banerjee
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a post increment operator is used here.so the answer is 5.
 
Henry Wong
author
Marshal
Pie
Posts: 21024
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • 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
 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic