包装类与基本类型
java数据类型分为基本数据类型与引用数据类型
包装类是将基本数据类型用一个类进行了一层包装,可以安装引用类型使用
| 基本数据类型 | 包装类 |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| boolean | Boolean |
| char | Character |
包装类与基本数据类型的转换
//基本数据类型转为包装类
Integer i1 = Integer.valueOf(123);
Double d = Double.valueOf(123);
//包装类转为基本数据类型
int i2 = Integer.valueOf(i1).intValue();
//基本数据类型转换为字符串
String str = Integer.toString(123);
//字符串转换为基本数据类型
int i3 = Integer.parseInt("123");
自动装箱和拆箱
自动装箱
基本数据类型赋值给引用变量时,系统可以自动将它包装为相应的包装类的对象
//自动装箱
Integer i1 = 1;
//实际调用
Integer i1 = Integer.valueOf(1); //在(-128~127)之间,调用相应包装类的valueof()
Integer i1 = new Integer(200); //不在(-128~127)之间,直接new对象
自动拆箱
将包装类的类型直接赋值给对应的基本数据类型的变量
Integer i = 100; //自动装箱
int a = i; //自动拆箱
int a = i.intValue(); //自动拆箱底层调用的xxxValue()方法

浙公网安备 33010602011771号