File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Reference variables and wrappers" Watch "Reference variables and wrappers" New topic

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

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

Joined: Sep 28, 2004
Posts: 20526

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.


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

Joined: Aug 03, 2008
Posts: 9465

Integer x=5;
Integer y=x;

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:
subject: Reference variables and wrappers
It's not a secret anymore!