包装类:
概念:基本数据类型的数据,使用起来非常的方便,但是没有对应的方法来操作这些数据,所以我们可以使用一个类把基本类型的数据包装起来,这个类叫包装类,在包装类中可以定义一些方法,用来操作基本类型的数据
装箱:
把基本类型的数据,包装到包装类中(基本类型的数据->包装类)
构造方法:
-
Integer(int value) 构造一个新分配的Integer对象,它表示指定的int值
-
Integer(String s) 构造一个新分配的Integer对象,它表示String参数所指示的int值
注:传递的字符串,必须是基本类型的字符串,否则会抛出异常 "100"正确, "a"抛异常
静态方法:
- static Integer valueof(int i) 返回一个表示指定的int值的Integer实
- static Integer valueof(String s) 返回保存指定的String值的Integer对象
拆箱:
在包装类中取出基本类型的数据(包装类->基本类型的数据)
成员方法:
- int intValue() 以int类型返回该Integer的值
演示代码:
public class Demo01Integer {
public static void main(String[] args) {
//装箱:把基本类型的数据,包装到包装类中(基本类型的数据->包装类)
// 构造方法
Integer in1 = new Integer(1);
System.out.println(in1);//重写了toString方法
Integer in2 = new Integer("1");
System.out.println(in2);
//静态方法
Integer in3 = Integer.valueOf(1);
System.out.println(in3);
Integer in4 = Integer.valueOf("1");
//Integer in4 = Integer.valueOf("a");//NumberFormatException数字格式化异常
System.out.println(in4);
//拆箱:在包装类中取出基本类型的数据(包装类->基本类型的数据)
int i = in1.intValue();
System.out.println(i);
}
}
自动装箱与自动拆箱
基本类型的数据和包装类之间可以自动的相互转换,JDK1.5之后出现的特性
演示代码
public class Demo2Integer {
public static void main(String[] args) {
/*
自动装箱:直接把int类型的整数赋值给包装类
Integer in = 1;相当于Integer in = new Integer(1);
*/
Integer in = 1;
/*
自动拆箱:in是包装类,无法直接参与运算,可以自动转换为基本类型的数据,再参与计算
in + 2;就相当于in.intValue()+ 2 = 3;
in = in + 2;就相当于in = new Integer(3)自动装箱
*/
in = in + 2;
//ArrayList集合无法直接存储整数,可以存储Integer包装类
ArrayList<Integer> list = new ArrayList<>();
list.add(1);//自动装箱 list.add(new Integer(1));
int a = list.get(0);//自动拆箱list.get(0).intValue();
}
}
基本类型与字符串之间的转换
基本类型->字符串
1.基本类型数据的值+"" 最简单的方式(工作中常用)
2.使用包装类中的静态方法
- static String toString(int i) 返回一个表示指定整数的String对象
3.使用String类中的静态方法
- static String valueOf(int i) 返回int参数的字符串表示形式
字符串->基本类型
使用包装类的静态方法parseXX(“字符串”);
- Integer类:static int parseInt(String s);
- Double类:static double parseDouble(String s);
- …
演示代码
public class Demo03Integer {
public static void main(String[] args) {
//基本类型与字符串之间的转换
String s1 = 100+"";
System.out.println(s1+200);
//使用包装类中的静态方法
String s2 = Integer.toString(100);
System.out.println(s2+200);
String s3 = String.valueOf(100);
System.out.println(s3+200);
//字符串->基本类型
int i = Integer.parseInt("100");
System.out.println(i+200);//300
double d = Double.parseDouble("8.8");
System.out.println(d+1.2);
int i2 = Integer.parseInt("a");//NumberFormatException 数字格式化异常
System.out.println(i2);
}
}