3

I can't figure out why the output is different.
The output is same only in the range -128 to 127.

public class Check {
    public static void main(String[ ] args) {
        Integer i1=122;
        Integer i2=122;

        if(i1==i2)
            System.out.println("Both are same");
        if(i1.equals(i2))
            System.out.println("Both are meaningful same");
    }
}

Output:
Both are same
Both are meaningful same

public class Check {
    public static void main(String[] args) {
        Integer i1=1000;
        Integer i2=1000;

        if(i1==i2)
            System.out.println("Both are same");
        if(i1.equals(i2))
            System.out.println("Both are meaningful same");
    }
}

Output: Both are meaningful same

sherb
  • 5,845
  • 5
  • 35
  • 45
nktsg
  • 143
  • 1
  • 9

1 Answers1

4

You've encountered a caveat in the Java language where autoboxing for "small" values has a slightly different rule than autoboxing. ("Small" in this case means a number in the range of 127 to -128, as in a signed byte in C.) From JLS 5.1.7 Boxing Conversion:

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

(Emphasis is mine.)

In the second example (where i1=i2=1000), the if(i1==i2) comparison results in false because the value of both objects is greater than 127. In that case == is a referential comparison, i.e. checking to see if the objects are actually the same object.

sherb
  • 5,845
  • 5
  • 35
  • 45