• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Boxing & unboxing

 
sakthi karthik
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i cant understand the following expalanation. can anyone please explain this


Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2) System.out.println("different objects");
if(i1.equals(i2)) System.out.println("meaningfully equal");

Produces the output:
different objects
meaningfully equal



Integer i3 = 10;
Integer i4 = 10;
if(i3 == i4) System.out.println("same object");
if(i3.equals(i4)) System.out.println("meaningfully equal");

This example produces the output:
same object
meaningfully equal

The equals() method seems to be working, but what happened with ==
and != ? Why is != telling us that i1 and i2 are different objects, when == is saying
that i3 and i4 are the same object? In order to save memory, two instances of the
following wrapper objects will always be == when their primitive values are the same:
Boolean
Byte
Character from \u0000 to \u007f (7f is 127 in decimal)
Short and Integer from -128 to 127
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You already posted the key to the answer:
Short and Integer from -128 to 127

Does 10 fall into this range? How about 1000?
 
sakthi karthik
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
now i understand , thank you
 
vinal sen
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But Karthik,

do remember



produces "not equal".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic