八大基础类型(都有对应的包装类型):
整数:byte(1字节)、short(2字节)、int(4字节)、long(8字节)
浮点数:float(4 byte)、double(8 byte)
字符型:char(2 byte)
布尔型:boolean(1 byte)
基本类型 | byte | short | int | long |
---|---|---|---|---|
位数 | 8位 | 16位 | 32位 | 64位 |
容量 | 255 | 65535 | 4*109 | 18*1018 |
表示范围 | -128~127 | -32768~32767 | 2*109 | 9*1018 |
两者的区别
1. 包装类型 可以 为null,但基本类型 不可以 为null
阿里巴巴Java开发手册:
数据库的查询结果可能为null,如果POJO的属性使用基本类型,会发生自动拆箱行为(比如把Integer转换为int),就会发生NullPointerException异常,故POJO的属性必须使用包装类型。
2. 包装类型 可用于 泛型,但基本类型不可以
例如:
List<int> list=null;//错误
List<Integer> list1=null;//正确
3. 包装类型的效率比基本类型低
基本类型在JVM中,存储于虚拟机栈中;包装类型变量属于引用型变量,在虚拟机栈中存储引用,在堆中存储具体的对象。
自动拆/装箱:
Integer a = 127;//自动装箱,是通过Integer.valueOf()完成的
Integer aa=new Integer(127);//手动装箱
int aaa=aa;//自动拆箱,是通Integer.intValue()完成的
int aaaa=aa.intValue();//手动拆箱
易错的面试题:
@Test
public void testEquals() {
int a1 = 128;
int a2 = 128;
System.out.println(a1 == a2);//true,基本类型存储在虚拟机栈中,而==比较虚拟机栈中的地址,则可以达到目的
Integer b1 = 127;
int b2 = 127;
Integer b3=127;
System.out.println(b1 == b2);//true
System.out.println(b1==b3);//true,当包装类型的值在-128-127之间,会使用到IntegerCache,相当于使用了栈中的数据,而==比较的是栈中的地址
Integer c1=128;
Integer c2=128;
System.out.println(c1==c2);//false
System.out.println(c1.equals(c2));//true
}