包裹类型就是将一个基本数据类型的数据转换成对象的形式,从而使得它可以像对象一样参与运算和传递。 一、基本数据类型与字符串的转换:
(1)基本数据类型—>字符串:
方法1:基本数据类型+""方法2:用String类中的valueof(基本数据类型)(2)字符串—>基本数据类型: 使用包装类中的静态方法: ①. int parseInt(“123”); ②. long parseLong(“123”); ③. boolean parseBoolean(“false”); ④. Character没有对应的parse方法. 如果字符串被Interger封装成一个对象,可以调用intValue(); 测试:
class WrapDemo{ public static void main(String[] args) { //基本数据类型---> 字符串: int i=123; System.out.println(i+"");//1.基本数据类型+"" System.out.println(String.valueOf(i));//2.用String类中的静态方法valueOf(基本数据类型); //字符串--->基本数据类型: String s = "321"; String s1 = "true"; //方法一:使用包裹类中的静态方法 System.out.println(Integer.parseInt(s)); //System.out.println(Integer.parseLong(s)); System.out.println(Boolean.parseBoolean(s1)); //方法二:如果被Interger封装,可以调用intValue. Integer j = new Integer("123"); System.out.println(j.intValue()); } } 二、基本数据类型和包装类的转换:(1)基本数据类型—>包装类 ①通过构造函数来完成 ②通过自动装箱 (2)包装类—>基本数据类型 ①通过intValue()来完成 ②通过自动拆箱 测试:
class WrapDemo2{ public static void main(String[] args) { //基本数据类型--->包装类: int i = 1;//①通过构造函数 Integer x = new Integer(i); System.out.println(x); Integer y = 3;//②通过自动装箱 System.out.println(y); //包装类--->基本数据类型: Integer j = new Integer(522); int x1 = j.intValue();//①通过int Value(); System.out.println(x1); int x2 = j;//②通过自动拆箱: System.out.println(x2); } }三、总结:
