Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java question about autoboxing and object equality / identity [duplicate]

public class Main { 
    /** 
      * @param args the command line arguments */ 
    public static void main(String[] args) { 
        // TODO code application logic here
        int a1 = 1000, a2 = 1000; 
        System.out.println(a1==a2);//=>true 
        Integer b1 = 1000, b2 = 1000;
        System.out.println(b1 == b2);//=>false 
        Integer c1 = 100, c2 = 100; 
        System.out.println(c1 == c2);//=>true 
    }

}

Why is b1 == b2 false and c1 == c2 true?

like image 386
OOP Avatar asked Jul 28 '10 10:07

OOP


1 Answers

Read this.

Java uses a pool for Integers in the range from -128 to 127.

That means if you create an Integer with Integer i = 42; and its value is between -128 and 128, no new object is created but the corresponding one from the pool is returned. That is why c1 is indeed identical to c2.

(I assume you know that == compares references, not values, when applied to objects).

like image 157
Felix Kling Avatar answered Nov 09 '22 22:11

Felix Kling