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
posted
0
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
posted
0
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
posted
0
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
posted
0
Thanks a lot for your replies uj nossnahoj .
Embla Tingeling
Ranch Hand
Joined: Oct 22, 2009
Posts: 237
posted
0
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.