0

Possible Duplicate:
Wrapper class and == operator

I have a puzzle from my friend. Here is it:

public class Test{
    public static void main(String[] args){
        Integer i = 1000; //10
        Integer y = 1000; //10      
        System.out.println(i == y);
    }
}

The result will be FALSE. That's right. But when replacing the i,y value by 10, the result is TRUE.

From what I've read, when the operator == is applied to reference variables, it will test whether they refer to the same object. I don't know why the results like that, but I guess the problem in numeric promotion. I really need a help. Thank every one.

Community
  • 1
  • 1
Hung Tran
  • 1,595
  • 2
  • 17
  • 17

1 Answers1

2

There is nothing promoted, since 10 and 1000, as numeric literal, are of type int.

But there is a value pool for small Integer-Objects, similar to the stringpool, since most values are small, or small values are used more often. But to limit the size of the pool, it only covers some values between -128 and 127.

As a rule of thumb: For Objects, always compare them with equals, only elementary types with ==.

user unknown
  • 35,537
  • 11
  • 75
  • 121