包装类
有时, 需要将 int 这样的基本类型转换为对象。所有的基本类型都冇一个与之对应的类。
例如,Integer 类对应基本类型 int。通常, 这些类称为包装器 ( wrapper ) 这些对象包装器类
拥有很明显的名字:Integer、Long、Float、Double、Short、Byte、Character 、 Void 和 Boolean (前
6 个类派生于公共的超类 Number)。对象包装器类是不可变的,即一旦构造了包装器,就不
允许更改包装在其中的值。同时, 对象包装器类还是 final , 因此不能定义它们的子类。 (以上来自Java核心卷I)
JDK5.0新特性:自动装箱与自动拆箱
自动装箱
即自动的将基本数据类型转换为相应的包装类型
自动拆箱
即自动的将包装类型转换为相应的基本数据类型
包装类、基本数据类型、String的相互转换
基本数据类型转化为包装类
1.调用包装类构造器
int num1=20;
Integer in1=new Integer(num1);
Float f1=new Float(12.3f);
Float f2=new Float(12.3);
Boolean b1=new Boolean(true);
Boolean b2=new Boolean("True");
2.自动装箱
int num1=10;
Integer in1=num1;
boolean b1=true;
Boolean b2=b1;
包装类转换为基本数据类型
1.调用对应包装类Xxx的xxxValue()方法
Integer in1=new Integer(12);
int i1= in1.intValue();
Float f1=new Float(12.3);
float f2=f1.floatValue();
Boolean b1=new Boolean(true);
boolean b2=b1.booleanValue();
2.自动拆箱
Integer in1=num1;
int num2 =in1;
基本数据类型、包装类转换为String类型
调用String重载的valueOf()方法
int num1=2;
//方式一:做连接运算
String str1=num1+"";
//方式二:String类的valueOf
float f1=12.3f;
String str2=String.valueOf(f1);
Double D1=new Double(12.6);
String str3=String.valueOf(D1);
String类型转换为基本数据类型、包装类
调用包装类中的paresXxx()方法
String str1="123";
int num1= Integer.parseInt(str1);
有不对的地方请各位大佬指出。