开发者

Numeric promotion and equality? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Wrapper class and == operator

I 开发者_如何学Gohave 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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜