• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

KB 235

 
sumaraghavi ragha
Ranch Hand
Posts: 118
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI

Please tell me why i1 and i2 are different and i3 and i4 are same

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

Thanks in advance
 
Vijitha Kumara
Bartender
Posts: 3908
9
Chrome Fedora Hibernate
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please check

http://forums.sun.com/thread.jspa?messageID=9407762
 
gobburi saikrishna
Ranch Hand
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Original question

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

Hi

in the first if statement i1 and i2 are compared as refrences and in second if statement values are compared.
In integer wrapper class the integers which are less than 128 are compared as values using (==) and any values after 128 are compared as refrences

class IntegerTest
{
public static void main(String[]args)
{
Integer i1=127;
Integer i2=127;
if(i1 ==i2)
System.out.print("same objects");
if(i1.equals(i2))
System.out.println("equally");
}
};

and
class IntegerTest
{
public static void main(String[]args)
{
Integer i1=128;
Integer i2=128;
if(i1 ==i2)
System.out.print("same objects");
if(i1.equals(i2))
System.out.println("equally");
}
};

Hope this should be clear
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic