整数类对象

Moh*_*sal 5 java

我有一个代码片段:

public class Test{
    public static void main(String args[]){
        Integer a = 100;
        Integer b = 100;
        Integer c = 5000;
        Integer d = 5000;

        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);
        if(a == b)
            System.out.println("a & b Both are Equal");
        else
            System.out.println("a & b are Not Equal");
        if(c == d)
            System.out.println("c & d Both are Equal");
        else
            System.out.println("c & d are Not Equal");
    }
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么输出是这样的?的Output是:
a & b Both are equal
c & d are not equal
我使用jdk1.7

Bjö*_*lex 7

这是由于虚拟机中的优化将小(常用)整数映射到重用的对象池.这个答案解释了一些细节.