int是基本数据类型之一,而Integer是一个包装类。
一、默认值
Integer的默认值为:null;
int的默认值为:0;
二、在内存中的存储
(1):因为定义a后,常量池中已经有“10”这个数据了,所以再次定义相同的数据时,就会将已经存有的数据的地址赋给变量b,所以a和b的地址是相等的。
public static void main(String[] args) {
int a = 10;
int b = 10;
System.out.println(a == b);//true
}
(2):当比较两个不是new出来的Integer对象时,因为Integer内部已经缓存了-128到127之间的数,所以如果两个变量的值在区间[-128,127]之间,比较的结果为true,否则为false。
public static void main(String[] args) {
Integer a = 10;
Integer b = 10;
Integer c = 128;
Integer d = 128;
System.out.println(a == b);//true
System.out.println(c == d);//false
}
(3):不是new出来的Integer对象指向常量池中的对象;而new出来的对象则指向堆中新建的对象,二者在内存中的地址是不一样的。
public static void main(String[] args) {
Integer a = 10;
Integer b = new Integer(10);
System.out.println(a == b);//false
}
(4):基本数据类型int和包装类型Integer(无论是否new)比较时,Integer会自动拆箱为int,然后再比较。(通常情况下,Integer和int比较,只要两个变量的值是相等的,结果都为true)。
public static void main(String[] args) {
int a = 10;
Integer b = 10;
Integer c = new Integer(10);
System.out.println(a == b);//true
System.out.println(a == c);//true
}