包装类的使用:
1、Java提供了8种基本数据类型对应的包装类,使得基本数据类型的变量具有类的特征
2、掌握的:基本数据类型、包装类、String三者之间的互相转换
Integer内部定义了IntegerCache结构,IntegerCache中定义了Integer[],保存了从-128~127范围的整数。如果我们使用自动装箱的方法,给Integer赋值的范围在-128~127内时,可以直接使用数组中的元素,不用再去new。目的:提高效率
向上转型与向下转型
各类型之间的转换
基本数据类型--->包装类:调用包装类的构造器
public void test1() {
int num1 = 10;
Integer in1 = new Integer(num1);
System.out.println(in1.toString());
Integer in2 = new Integer("123");
System.out.println(in2.toString());
Float f1 = new Float(12.3f);
Float f2 = new Float("12.3");
System.out.println(f1);
System.out.println(f2);
Boolean b1 = new Boolean(true);
Boolean b2 = new Boolean("true");
Boolean b3 = new Boolean("true123");
System.out.println(b3);//false
}
包装类--->基本数据类型:调用包装类的xxxValue()
public void test2() {
Integer in1 = new Integer(12);
int i1 = in1.intValue();
System.out.println(i1 + 1);
Float f1 = new Float(12.3);
f1.floatValue();
}
JDK 5.0 新特性:自动装箱与自动拆箱
public void test3() {
//自动装箱:基本数据类型到包装类
int num2 = 10;
Integer in1 = num2;//自动装箱
boolean b1 = true;
Boolean b2 = b1;//自动装箱
//自动拆箱:包装类到基本数据类型
System.out.println(in1.toString());
int num3 = in1;
}
基本数据类型、包装类-->String类型:调用String重载的valueOf(Xxx xxx)
public void test4(){
int num1 = 10;
//方式1:连接运算
String str1 = num1 + "";
//方式2:
float f1 = 12.3f;
String str2 = String.valueOf(f1);
Double d1 = new Double(12.4);
String str3 = String.valueOf(d1);
}
String类型-->基本数据类型、包装类:调用包装类的parseXxx()
public void test5() {
String str1 = "123";
//可能会报NumberFormatException的错误
int num2 = Integer.parseInt(str1);
System.out.println(num2 +1);
String str2 = "true";
boolean b1 = Boolean.parseBoolean(str2);
System.out.println(b1);//true
String str3 = "true1";
boolean b2 = Boolean.parseBoolean(str3);
System.out.println(b2);//false
}