views:

238

answers:

5
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?

A: 

The answer you want is here

Pere Villega
A: 

You can find the answer here:

http://stackoverflow.com/questions/1995113/strangest-language-feature in the 6th answer.

Edit: sorry not exatly the answer. The point is that == compares references, not values when you use it with Integer. But with int "==" means equals.

Zoltan Balazs
+23  A: 

Read this.

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

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).

Felix Kling
thank Felix Kling very much . I understood this code
OOP
That doesn't explain why a1==a2.
simon
The question was about `b1==b2` and `c1==c2`, if I'm not mistaken.
Justin Ardini
a1==a2 because they are primitive "int" types, not the Integer object type
Matt N
A: 

Because Integer is for a few low numbers like enumeration so there is always same instance. But higher numbers creates new instances of Integer and operator == compares their references

Gaim
+7  A: 

The correct answers have already been given. But just to add my two cents:

Integer b1 = 1000, b2 = 1000;

This is awful code. Objects should be initialized as Objects through constructors or factory methods. E.g.

 // let java decide if a new object must be created or one is taken from the pool
Integer b1 = Integer.valueOf(1000);

or

 // always use a new object
 Integer b2 = new Integer(1000);

This code

Integer b1 = 1000, b2 = 1000;

on the other hand implies that Integer was a primitive, which it is not. Actually what you are seeing is a shortcut for

Integer b1 = new Integer(1000), b2 = new Integer(1000);

and two different objects will never be ==. So although 1000 = 1000, b1 != b2. This is the main reason why I hate auto-boxing.

seanizer
Thank seanizer very much !
OOP