Java提供了两个类型系统,基本类型与引用类型,使用基本类型在于效率,在很多情况下,会创建对象使用,因为对象可以做更多的功能,如果想要我们的基本类型像对象一样操作,就可以使用基本类型对应的包装类(在java.lang包下)
基本类型 | 对象的包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
装箱与拆箱
- 装箱(基本数据类型->包装类)
把基本类型数据包装到包装类中
Integer it = new Integer(10);//构造方法
System.out.println(it);//输出:10
Integer itv = Integer.valueOf(10);//静态方法
System.out.println(itv);//输出:10
- 拆箱(包装类->基本数据类型)
在包装类中取出基本数据类型
Integer it = new Integer(10);//构造方法
int i = it.intValue();
System.out.println(itv);//输出:10
自动装箱与自动拆箱
基本类型的数据和包装类之间可以自动的相互转换,JDK1.5之后出现的新特性
2. 自动装箱
直接把int类型的整数赋值给包装类
Integer in = 6;//就相当于Integer in = new Integer(6);
- 自动拆箱
包装类无法直接参与运算,可以自动转换为基本类型的数据,在参与计算
//in + 2 相当于in.intValue() + 2 = 8
//in = in + 2 相当于in = new Interger(8)自动装箱
Integer in = 6;
in = in + 2;
典型的例子
ArrayList<Integer> list = new ArrayList<>();
list.add(1);//自动装修:list.add(new Integer);
int i = list.get(0);//自动拆箱:list.get(0).intValue();
基本类型与字符串之间的转换
- 基本类型转换为String
总共有三种方式,
a.最简单的一种:基本类型直接与”“(空)相连接即可:如:88+”“
b.使用包装类中的静态方法:static String toString(int i)
c.使用String类的静态方法:static String valueOf(int i) - String转换为基本类型
使用包装类的静态方法parseXX(“字符串”)
Integer类:static int parseInt(String s)
Double类:static double parseDouble(String s)
…