Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference comparison using == operator [duplicate]

Tags:

java

scjp

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?

like image 222
kittu Avatar asked Nov 01 '22 05:11

kittu


1 Answers

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.

like image 168
Maroun Avatar answered Nov 15 '22 06:11

Maroun