• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Equality Problem

 
Ramesh Sahu
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class test {
public static void main(String[] args) {
test inst_test = new test();
int i1 = 2000;
int i2 = 2000;
int i3 = 2;
int i4 = 2;
Integer Ithree = new Integer(2); // 1
Integer Ifour = new Integer(2); // 2
System.out.println( Ithree == Ifour );
inst_test.method( i3 , i4 );
inst_test.method( i1 , i2 );
}
public void method( Integer i , Integer eye ) {
System.out.println(i == eye );
}
}

The output comes out to be :
false
true
false

Can anyone please explain the result & the concept behind it ??
 
Paul Beckett
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the == checks to see if both references are for the same object.

iThree and iFour are different objects so the result is false. That should be fairly easy to understand (notice the use of "new" when creating the objects).

When an int is boxed into an Integer as is happening when you call "method" then if the int is between -128 and 127 inclusive then the jvm uses a cache. So all boxed references of the same int in that range will refer to the same object.


All the tests will be true if you use .equals() instead of ==.

[ July 29, 2008: Message edited by: Paul Beckett ]
[ July 29, 2008: Message edited by: Paul Beckett ]
 
Sandeep Bhandari
Ranch Hand
Posts: 201
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please note that this will result in compiler error in case of jdk1.4

its autoboxing of jdk1.5 which makes this code work.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic