This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Wrapper instances question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Wrapper instances question" Watch "Wrapper instances question" New topic
Author

Wrapper instances question

patrick avery
Ranch Hand

Joined: Sep 12, 2008
Posts: 46
This one from Inquisition (SCJP 5 quiz by Mark DeChamps) confuses me:



The answer is 5 but my incorrect reasoning led me to say 6...
It looks like Integer y=x; creates a 2nd object, whereas I interpreted it as assigning y to the same object that x points to.

I.e. in the code below why does Integer y=x; create a new object while AClass m2 = m1; just points m2 to the same object as m1?



SCJA 96%
SCJP 6 88%
skipping SCJD to work on passing SCWCD
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18545
    
  40

The answer is 5 but my incorrect reasoning led me to say 6...
It looks like Integer y=x; creates a 2nd object, whereas I interpreted it as assigning y to the same object that x points to.


Your reasoning for this line is actually correct. When you assign a reference to another reference, it doesn't create a new object.

It's the next line that is the issue. Integer objects are immutable, so when you do y++ on an Integer object, the value must be unboxed, incremented, and reboxed. It is this boxing that changes the reference to another Integer object.

Henry
[ December 09, 2008: Message edited by: Henry Wong ]

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
patrick avery
Ranch Hand

Joined: Sep 12, 2008
Posts: 46
Thanks, Henry!! That makes perfect sense to me now.
[ December 09, 2008: Message edited by: patrick avery ]
 
Consider Paul's rocket mass heater.
 
subject: Wrapper instances question
 
Similar Threads
Abstract class??
Dan's questions : static variable
doubts on try and finally block
Clarification on Q6 Self-Test Chapter 3 K&B SCJP5
finding the intersection of two lines- for a junit test case