一,包装类的概念
什么是包装类
基本数据类型使用起来非常方便,但是没有对用的方法来操作这些基本数据类型,可以使用一个类,把基本类型的数据装起来,在类中定义一些方法,这个类叫做包装类。
包装类不止可以存储数据,而且也可以提供一些方法的操作
包装类对应的八种基本数据类型
在Java中有8种基本数据类型,Java为这8种基本数据类型提供了8种包装类
除了int和char的包装类写法稍有不同,其余均只需首字母大写即可。
二,装箱和拆箱,自动装箱和自动拆箱
基本类型与对应的包装类对象之间,来回转换的过程称为”装箱“与”拆箱“;
- 装箱:从基本数据类型转换为对应的包装类对象。
- 拆箱:从包装类对象转换为对应的基本类型
- int装箱的时候自动调用Integer的valueOf(int)方法;
- Integer拆箱的时候自动调用Integer的intValue方法。
装箱是通过调用包装器类的 valueOf 方法实现的
拆箱是通过调用包装器类的 xxxValue 方法实现的,xxx代表对应的基本数据类型(int,short,long,double,byte,char,float,boolean)。
//基本数据类型和包装类型
int a1=5;
Integer a2=new Integer(5);
System.out.println(a1);
System.out.println(a2);
//装箱
Integer a3=new Integer(a1);
Integer a4=Integer.valueOf(a1);
//拆箱
int a5=a3.intValue();
//自动装箱与自动拆箱
//自动装箱
Integer a6=a1;
//自动拆箱
int a7=a3;
三,基本数据类型和字符串的相互转换
基本类型-->字符串:
- 基本类型数据的值+“”最简单的方式,最常用。如果有两个基本数据类型的值那么它们相加再加上字符串。
- 使用包装类中的静态方法:static String toString(int i)返回一个表示指定整数的String对象。
- 使用String类中的静态方法:static String valueOf(int i)返回int参数的字符串表示形式。
public static void main(String[] args) {
//基本数据类型可以自动转换为字符串
System.out.println(1+"2");
System.out.println(1+2+"3");
}
字符串-->基本类型数据 :
- 使用包装类的静态方法parseXX(“字符串”)
- 可以按照指定的进制进行一个转换
public static void main(String[] args) {
//字符串需要手动进行基本数据类型转换
int n=Integer.parseInt("123");
double d=Double.parseDouble("3.14");
System.out.println(n);
System.out.println(d);
System.out.println("-------");
int n1=Integer.parseInt("8D3FE",16);
System.out.println(n1);
}
运行结果如下: