5
public class AutoBoxingAndUnBoxing 
{
    public static void main(String[] args) 
    {
        Integer x = 127;
        Integer y = 127;
        System.out.println(x == y);//true

        Integer a = 128;
        Integer b = 128;
        System.out.println(a == b);//false
        System.out.println(a); // prints 128
    }
}

How come x==y is true and a==b is false? If it is based on the value(Integer -128 To 127) then 'a' should print -128 right?

kittu
  • 6,662
  • 21
  • 91
  • 185

1 Answers1

2

When comparing Integer objects, the == operator might work only for numbers between [-128,127]. Look at the JLS:

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Since that values you're comparing are not in the mentioned range, the result will be evaluated to false unless you use Integer#equals.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • ok but what will be the value after 127 if then range is -128 to 127? – kittu Apr 26 '15 at 07:16
  • @kittu what do you mean "the value"? These values are cached due to performance issues, values that are out of that range should be compared using `equals`. – Maroun Apr 26 '15 at 07:17
  • I mean how `a==b` is false in my case? What is happening internally to make it false? :/ – kittu Apr 26 '15 at 07:21
  • @kittu Because `a` and `b` are not primitives, they're *objects*. Comparing objects should be done using `equals`, it works for 127 because the value is cached, and `==` can (not always) handle it. – Maroun Apr 26 '15 at 07:22