File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wrapper instances question

 
patrick avery
Ranch Hand
Posts: 46
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

 
Henry Wong
author
Marshal
Pie
Posts: 20829
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
patrick avery
Ranch Hand
Posts: 46
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Henry!! That makes perfect sense to me now.
[ December 09, 2008: Message edited by: patrick avery ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic