Reference comparison using the == operator

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 } } 

Why is x==y true and a==b false? If it is based on a value ( Integer -128 To 127 ), then 'a' should print -128 correctly?

+5
source share
1 answer

When comparing Integer objects, the == operator can only work for numbers between [-128,127]. Check out JLS :

If the value of p placed in the field is true, false, a byte or char in the range \ u0000 to \ u007f, or int or a short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two conversion conversion boxes . It always happens that r1 == r2.

Since these values ​​that you are comparing are not in the specified range, the result will be evaluated to false if you are not using Integer#equals .

+2
source

All Articles