一:包装类的概念
概述:
基本数据类型使用方便,但是没有对应的方法来使用这些数据,因此我们可以使用一个类,把基本数据类型包装起来,这个类就叫做“包装类”。在包装类中可以定义一些基本的方法,来操作基本类型的数据。
包装类对应的八种基本数据类型
基本数据类型 | 对应的包装类(java.lang包) |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
二:装箱与拆箱
装箱:从基本类型转换为包装类对象
public static void main(String[] args) {
int a = 10;
Integer b = a; //自动装箱
}
拆箱:从包装类对象转换为对应的基本类型
public static void main(String[] args) {
Integer c = 11;
int d = c; //自动拆箱
}
代码示例:
//基本数据类型和包装类型
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;
三:基本类型与字符串类型之间的相互转换
包装类可以把基本类型的数据转换为字符串形式
基本类型->字符串(String)
代码示例:
public static void main(String[] args) {
Integer a=10;
String b=a.toString();
System.out.println(b+1);
String c=Integer.toString(a);
System.out.println(c+1);
String d=a+"";
System.out.println(d+1);
}
运行结果:
字符串(String)->基本类型
//字符串(String)->基本类型
int n = Integer.parseInt("123");
double h = Double.parseDouble("3.14");
System.out.println(n);
System.out.println(h);
System.out.println("-------");
int n1 = Integer.parseInt("8D3FE", 16);
System.out.println(n1);
运行结果: