1

Possible Duplicate:
Java question about autoboxing and object equality / identity

Integer i1 = 10;
Integer i2 = 10;
Integer i3 = 210;
Integer i4 = 210;

if(i1 ==i2){
      System.out.println("True");
}else{
      System.out.println("False");
}
if(i3==i4){
       System.out.println("True");
}else{
       System.out.println("False");
}
if(Integer.valueOf(10) ==Integer.valueOf(10)){
       System.out.println("True");
}else{
      System.out.println("False");
}
if(Integer.valueOf(210) ==Integer.valueOf(210)){
       System.out.println("True");
}else{
       System.out.println("False");
}

The answer is

True

False

True

False

Why it is giving false for 2 and 4 condition ?

Community
  • 1
  • 1
Rahul Agrawal
  • 8,913
  • 18
  • 47
  • 59
  • 2
    You can see the solution here: http://stackoverflow.com/questions/10223555/java-comparison-not-working-when-integer-larger-than-128 – Averroes Jul 13 '12 at 11:49
  • 1
    Actually http://stackoverflow.com/questions/5117132/integer-wrapper-objects-share-the-same-instances-only-within-the-value-127 is probably the better close target. – Joachim Sauer Jul 13 '12 at 11:50
  • Its an Object, but not as we know it – MadProgrammer Jul 13 '12 at 12:24
  • In JDK1.5 there is a new concept called Caching Integer Objects. In JDK1.5 the JVM caches Integer objects from range of -128 to 127 . So every time an integer object is create with value between the above mentioned range same object will be returned instead of creating the new object. – Rahul Agrawal Jul 13 '12 at 12:32

4 Answers4

5

Use .equals() to compares Integer.== compares refrences equality

Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
3

== compares instances not values. Use int instead of Integer and it will work

juergen d
  • 201,996
  • 37
  • 293
  • 362
2

Note that Integer is an object, not a primitive. You're comparing different object instances.

For this particular example, it's worth reading about boxing.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

In Java use the Object function Object.equals(Object) to compare objects. That comparison would only work correctly using the primitive int.

Nuno
  • 1,163
  • 1
  • 11
  • 15