包装类: 基本数据类型使用起来非常方便,但是没有对应的方法来操作这些基本类型的数据,可以使用一个类把基本类型的数据装起来,在类中定义一些方法,这个类叫做包装类,我们可以使用类中的方法来操作这些基本类型的数据
1 装箱与拆箱
装箱:把基本类型的数据,包装到包装类中(基本类型的数据- >包装类)
构造方法: Integer(int value) 构造一-个新分配的Integer 对象,它表示指定的int 值。 Integer(String s)构造一个新分配的Integer 对象,它表示String参数所指示的int值。 传递的字符串, 必须是基本类型的字符串,否则会抛出异常”100” 正确”a” 抛异常
静态方法: static Integer value0f(int i)返回一个表示指定的int 值的Integer 实例。 static Integer valueOf(String 5)返回保存指定的String的值的Integer对象。
拆箱:在包装类中取出基本类型的数据(包装类- >基本类型的数据)
成员方法: int intValue() 以int类型返回该Integer 的值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public class Demo01Integer { public static void main (String[] args) { Integer in1 = new Integer( value: 1 ); System.out.println(in1); Integer in2 = new Integer( s:" 1" ) ; System.out.println(in2); Integer in3 = Integer.vaLueOf(1 ); System.out.println(in3); Integer in4 = Integer.value0f("1" ); System.out.println(in4); int i = in1.intValue(); System.out.println(i); } }
2 自动装拆箱 JDK1.5以后实现了自动装拆箱
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public class Demo02Ineger { public static void main (String[] args) { Integer in = 1 ; in = in+2 ; ArrayList<Integer> list = new ArrayList<>(); list.add(1 ); int a = list.get(0 ); list.get(0 ). intValue(); } }
3 基本类型与字符串转换
基本类型的值+”” 最简单的方法(工作中常用)
包装类的静态方法toString(参数),不是objec t类的tostring()重载 static String toString(int i)返回一个表示指定整数的String 对象。
String类的静态方法value0f(参数) static String valueOf(int i) 返回int 参数的字符串表示形式。
字符串(String)->基本类型 使用包装类的静态方法parseXXX( “字符串”); Integer类: static int parseInt(String s) Double类: static double parseDouble(String s)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public class Demo03Integer {public static void main (String[] args) {int i1 = 100 ;String s1 = i1+"" ; System. out . println(s1+200 ); String s2 = Integer. toString( i: 100 ); System. out . print1n(s2+200 ); String s3 = String. value0f(100 ); System. out .println(s3+200 ); int i = Integer . parseInt(s1);System. out . print1r(i-10 ); int a = Integer . parseInt( "a" );System. out . println(a); }