File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
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: 19070
    
  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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Wrapper instances question