aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Reference variables and wrappers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Reference variables and wrappers" Watch "Reference variables and wrappers" New topic
Author

Reference variables and wrappers

Vyas Sanzgiri
Ranch Hand

Joined: Jun 16, 2007
Posts: 686

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


===Vyas Sanzgiri===
My Blog
Sambit Banerjee
Greenhorn

Joined: Jul 29, 2008
Posts: 18
a post increment operator is used here.so the answer is 5.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9304
    
  17

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.


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reference variables and wrappers