aspose file tools*
The moose likes Beginning Java and the fly likes Regarding wrappers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Regarding wrappers" Watch "Regarding wrappers" New topic
Author

Regarding wrappers

Venu Chakravorty
Ranch Hand

Joined: Aug 19, 2009
Posts: 46
The following piece of code makes me think that: "i1" refers to "new Integer(5)" and i2 refers to the same "new Integer(5)" through "i1", i.e. "i2" refers to "i1" which refers to the "new Integer(5)". At the statement "i1++", "i1" gets unwrapped, incremented and rewrapped and refers to a different object, but "i2" still refers to "i1" (thus they refer to the same object), so the second "i1 == i2" should also return true, but it doesn't.


thanks and regards venu.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18717
    
  40

At the statement "i1++", "i1" gets unwrapped, incremented and rewrapped and refers to a different object, but "i2" still refers to "i1" (thus they refer to the same object), so the second "i1 == i2" should also return true, but it doesn't.


You have to understand the distinction between reference and object.

i2 = i1 ... means assign the i2 reference to the object that is currently referenced by i1. So, after that operation both the i1 and i2 reference refers to the same object. If you change the i1 reference to something else, it doesn't automatically change the i2 reference.

Henry


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

Joined: Aug 19, 2009
Posts: 46
Thanks Henry.
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
venu chakravorty wrote:The following piece of code makes me think that: "i1" refers to "new Integer(5)" and i2 refers to the same "new Integer(5)" through "i1", i.e. "i2" refers to "i1" which refers to the "new Integer(5)".


What you're describing is an assignment by reference, but Java doesn't have that. In Java everything is done by value. Variables are assigned by value and parameters are passed by value. Nothing is done by reference. Still there word reference is used in Java but here it means "pointer to an object". You should be careful to make these distinctions,

* Java never assigns variables by reference. Java always assigns variables by value and the value is either a references (a pointer) or a primitive.

* Java never passes parameters by reference. Java always passes parameters by value and the value is either a references (a pointer) or a primitive.

So "by reference" is completely banned from Java. A reference in Java is a pointer.
Venu Chakravorty
Ranch Hand

Joined: Aug 19, 2009
Posts: 46
Thanks uj.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Regarding wrappers