Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

== with Boxing

 
sandeeep shinde
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 237
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 237
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for your replies uj nossnahoj .
 
Embla Tingeling
Ranch Hand
Posts: 237
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic