基本数据类型:
- 不是对象
- 不需要实例化new
- 保存在栈上,直接存储的值
- 有特殊默认值(int的默认值为0)
- 同一基本类型的不同变量的内存地址一样
- 运算可以直接进行
包装类:
- 是对象,有属性和方法
- 需要实例化new
- 保存在堆上,存储实例对象的引用,也就是内存地址
- 所有默认值都是null
- 实例化得到的同一包装类型相同值得不同变量的内存地址不一样
- 需要先拆箱为基本类型然后才能进行运算
分类 | 基本数据类型 | 包装类 | 长度 | 位数 | 最小值 | 最大值 |
---|---|---|---|---|---|---|
整型 | byte | Byte | 1字节 | 8 | -128(-2^7) | 127(2^7 - 1) |
short | Short | 2字节 | 16 | -32768(-2^15) | 32767(2^15 - 1) | |
int | Integer | 4字节 | 32 | -2,147,483,648(-2^31) | 2,147,485,647 (2^31 - 1) | |
long | Long | 8字节 | 64 | -9,223,372,036, 854,775,808(-2^63) | 9,223,372,036, 854,775,807 (2^63 -1) | |
浮点型 | float | Float | 4字节 | 32 | -3.40E+38 | 3.40E+38 |
double | Double | 8字节 | 64 | -1.79E+308 | 1.79E+308 | |
字符型 | char | Character | 2字节 | 16 | \u0000 (0) | \uFFFF (65,535) |
布尔型 | boolean | Boolean | 1字节 | 8 | false | true |
拆箱和装箱
拆箱:把包装类转换成基本数据类型的过程
装箱:把基本数据类型转换成包装类的过程
//Java提供了自动拆箱和自动装箱功能
Integer a = 10; //自动装箱Integer a = Integer.valueOf(10); //等价形式
int b = a; //自动拆箱int b =a.intValue(); //等价形式
valueOf()方法的缓存机制:编译器提前缓存,直接从缓存里拿,节省内存
- Integer的-128 ~ 127 之间的整数
- Boolean的布尔值true和false
- Character 在 '\u0000' ~ '\u007F' 之间的值(0 ~ 127)
Integer a = 100, b = 100;
System.out.println(a == b); // Output: true
Integer c = 400, d = 400;
System.out.println(c == d); // Output: false
场景一:将基本数据类型放入集合类:基本数据类型放入集合类中会自动装箱
List<Integer> list = new ArrayList<>();
list.add(1);
//反编译为list.add(Integer.valueOf(1));
场景二:包装类型与基本类型比较大小:先将包装类型进行拆箱为基本数据类型然后再比较
Integer a = 1;
System.out.println(a==1?"等于":"不等于");
//反编译为System.out.println(a.intValue()==1?"等于":"不等于");
Boolean b = 1;
System.out.println(b?"真":"假");
//反编译为System.out.println(b.booleanValue()?"真":"不假");
场景三:包装类型的运算:会被自动拆箱成基本数据类型进行运算
Integer a = 1 ; //反编译为Integer a = Integer.valueOf(1);
Integer b =2 ; //反编译为Integer a = Integer.valueOf(2);
System.out.println(a+b);
//反编译为System.out.println(a.intValue()+b.intValue());
场景四:三目运算符的应用:null对象的自动拆箱导致NullPointerException异常。
boolean a =true;
boolean b =false;
Boolean c = null;
boolean x = a ? c : b;
//反编译为boolean x = a ? c.booleanValue() : b; =>NullPointerException异常
场景五:函数参数与返回值
//自动拆箱
public int getNumberOne(Integer n){
return n;
}
//自动装箱
public Integer getNumberTwo(int n){
return n;
}