目录
1.为什么要有包装类(或封装类)
为了使基本数据类型的变量具有类的特征,引入包装类。
2.基本数据类型与对应的包装类:
byte --> Byte
short --> Short
int --> Integer
long --> Long
float --> Float
double --> Double
以上父类为Number
boolean --> Boolean
char --> Character
3.基本数据类型与包装类之间的相互转换:
基本数据类型 ----> 包装类:调用包装类的构造器
int num1 = 10;
Integer in1 = new Integer(num1)
System.out.println(in1.toString()); //10
Integer in2 = new Integerr("123");
System.out.println(in2.toString()); //123
//报异常
Integer in3 = new Integer("123abc");
System.out.println(in3.toString());
//特殊情况
Boolean b1 = new Boolean(true); //true
Boolean b2 = new Boolean("true"); //true
Boolean b3 = new Boolean("true123"); //false 并不会报错
}
Boolean类型源码
包装类 ----> 基本数据类型:调用包装类的xxxValue()
Integer in1 = new Integer(12);
int i1 = in1.intValue();
System.out.println(i1) //12
4.jdk5.0新特性:自动拆箱与自动装箱
**自动装箱:**基本数据类型 ------> 包装类
int num2 = 10;
Integer in1 = num2 //自动装箱;
boolean b1 = true;
Boolean b2 = b1; //自动拆箱
**自动拆箱:**包装类 ------> 基本数据类型
int num3 = in1; //自动拆箱
有自动装箱和自动拆箱后基本数据类型和包装类可以看成一个整体。
5.基本数据类型、包装类 与 String类型之间的转换:
基本数据类型、包装类 ----> String类型:调用String重载的valueOf(Xxx xxx)
//方式一:字符串的拼接
int num1 = 10;
String str1 = num1 + "";
//方式二:调用String重载的valueOf(Xxx xxx)
float f1 = 12.3f;
String str2 = String.valueOf(f1); //"12.3"
String类型 -----> 基本数据类型、包装类 :调用包装类的parseXxx()
String str1 = "123";
int num2 = Integer.parseInt(str1); //调用包装类的parseXxx()
System.out.println(num2);