基本类型VS包装类
8种基本类型
byte short int long float double char boolean
对应的包装类
Byte Short Integer Long Float Double Character Boolean
基本类型不具备对象的特征,解决方法:提供包装类(可以像操作对象那样操作包装类)
包装类提供2类方法:
1、本类型和其他基本类型进行转换
2、字符串和本类型及包装类进行转换
自动装箱和拆箱
装箱:把基本类型转换成包装类,使其具有对象的性质
int i = 6;
Integer x = new Integer(i);//手动装箱
Integer y = i;//自动装箱
拆箱:和装箱相反
Integer i = new Integer(6);
int x = i.intValue();//手动拆箱为int类型
int y = i;//自动拆箱为int类型
基本类转字符串的三种方法
- 包装类的toString()方法
- String类的valueOf()方法
- 基本类型 + 空字符串
int i = 6;
String str1 = Integer.toString(i);
String str2 = String.valueOf(i);
String str3 = i + "";
字符串转基本类的两种方法
- 包装类的parseXxx()方法
- 包装类的valueOf()方法
String str = "6";
int i = Integer.parseInt(str);
int j = Integer.valueOf(str);