0

I wanted to check Integer equality in my application but came across a strange behavior. At some point my application was working correctly but at some point it was failing. So I just written a test code over here

public class EqualityTest {

     public static void main(String args[]) {
           Integer a = 100;
           Integer b = 100;
           Integer c = 1000;
           Integer d = 1000;
           if (a == b) {
                 System.out.println("a & b are Equal");
           }
           else {
                 System.out.println("a & b are Not Equal");
           }

           if (c == d) {
                 System.out.println("c & d are Equal");
           } else {
                 System.out.println("c & d are Not Equal");
           }
     }
}

Output

a & b are Equal
c & d are Not Equal

here my question is why c and d are not equal?

PakkuDon
  • 1,627
  • 4
  • 22
  • 21
eatSleepCode
  • 4,427
  • 7
  • 44
  • 93

4 Answers4

6

Integer uses caching of small values in range of -128 to 127, and so you get same instance for small values such as 100.

For the values outside this range, a new Integer instance is created and returned.

Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
  • and the cached value is between -128 to 127.. Anything within this range, you get the same object (so 100 gives equal.) and anything outside this range, a new object is returned (2 new Integer objects with value 1000 .. So you get false..) – TheLostMind Jan 21 '14 at 06:46
3

Integer is mutable class and keep around -128 to 127 integers in cache. So == will work on Integers -128 <= i <= 127

Each time you create Integer with this range it will return you the same object previously created.

For Java 7 implementation could be achieved with system property:

-Djava.lang.Integer.IntegerCache.high=<size>
Talha Ahmed Khan
  • 15,043
  • 10
  • 42
  • 49
-3

Integer is an Object. You should use equal instead of == like

if(a.equal(b)){
...
}
Ryker.Wang
  • 757
  • 1
  • 9
  • 18
-4
        Integer a = 100;
        Integer b = 100;
        Integer c = 1000;
        Integer d = 1000;
        if (a.equals(b)) {
            System.out.println("a & b are Equal");
        }
        else {
            System.out.println("a & b are Not Equal");
        }
        if (c.equals(d)) {
            System.out.println("c & d are Equal");
        } else {
            System.out.println("c & d are Not Equal");
        }

==means their pointer or reference equal,not value equal.You should call .equals method

David Hx
  • 125
  • 1
  • 2
  • 12