public class Test {
public static void main(String[] args) {
int a = 10;
int b = 200;
Integer a1 = 10;
Integer b1 = 200;
Integer a2 = new Integer(a1);
Integer b2 = new Integer(b1);
System.out.println(a == a1);
System.out.println(a == a2);
System.out.println(a1== a2);
System.out.println(b == b1);
System.out.println(b == b2);
System.out.println(b1 == b2);
}
}
这段程序的运行结果为:
true
true
false
true
true
false
解析:
- 对于a == a1,使用a来比较,Integer a1会自动拆箱,此时 == 比较的是值,都为10,所以为true
- 对于a == a2,使用a来比较,a2也会自动拆箱,此时 == 比较的是值,都为10,所以为true
- a2重新new了一个对象,比较的是地址,两个对象地址不同,所以是false
- 同1
- 同2
- 同3