It's not a secret anymore!*
The moose likes Beginning Java and the fly likes == with Boxing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "== with Boxing" Watch "== with Boxing" New topic
Author

== with Boxing

sandeeep shinde
Greenhorn

Joined: Aug 26, 2009
Posts: 13
Please take a look at the code below



The output produces "false true" .
If the values in the wrappers being compared are in the range -128 to 127 the == should return true.
But how does it return false here.
If I comment the statement i2 = i2.intValue(); the == returns true.
Can somebody please guide me on this?
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
sandeeep shinde wrote:Can somebody please guide me on this?


Change this

Integer i = new Integer(25);

to this,

Integer i = 25;

If you do that, i will be assigned the unique reference associated with the 25 literal. Whenever you use the new operator a new object will be created so if you do new Integer(25) this refernce will differ from the one associated with 25.
sandeeep shinde
Greenhorn

Joined: Aug 26, 2009
Posts: 13
Ok. So when methodB is called the i2 has reference to same object as startingI. But when I am doing i2 = i2.intvalue ; the reference to the literal 25 is getting assigned to i2.
Am I correct?
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
sandeeep shinde wrote:Ok. So when methodB is called the i2 has reference to same object as startingI. But when I am doing i2 = i2.intvalue ; the reference to the literal 25 is getting assigned to i2.
Am I correct?


Yes.

i2 = i2.intValue();

Whatever reference was held in i2, after the above operation i2 will refer to the unique object representing the i2.intValue() value (if it's within -128 through 127).
sandeeep shinde
Greenhorn

Joined: Aug 26, 2009
Posts: 13
Thanks a lot for your replies uj nossnahoj .
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
You're wellcome.

Note that although this behavior is defined by Java it's easy to get it wrong so it's better not to write code that depends on it.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: == with Boxing
 
Similar Threads
scjp1.5
Changing the return type of a method causes a runtime failure
Assertions Problem