1
class Test {
    public static void main (String[] args) {
        Integer i=128;
        Integer j=128;
        if(i==j){
            System.out.println("Equal");
        }
        else{
            System.out.println("Not Equal");
        }

    }

}

This is my Code. In this case It will show output as Not equal. But if I pass input less than 128 then it will give output as Equal.

Sergii Lagutin
  • 10,561
  • 1
  • 34
  • 43
  • http://stackoverflow.com/questions/22529843/java-implementation-of-for-integer-objects-with-value-from-128-to-127?lq=1 – griFlo Aug 10 '15 at 07:40
  • 1
    Read more about [integer cache](http://stackoverflow.com/questions/3130311/weird-integer-boxing-in-java) – Sergii Lagutin Aug 10 '15 at 07:40

1 Answers1

3

It's because you're comparing Integer instances (which are objects) with ==. When you compare objects with ==, you're checking that they're the same object, not that they're equivalent.

So why does it work with values less than 128? Because the JVM caches and reuses Integer instances for those values. You're using autoboxing by assigning primitives to Integer variables, and boxing uses Integer.valueOf. From the JavaDoc:

This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

But for other values, it (probably) creates new instances as you go.

For what you're doing, use int primitives instead of Integer instances. If you ever need to use Integer instances, compare them with equals instead of ==.

if (i.equals(j))
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875