- Java中的包装类都是用 final 修饰的,是无法被继承的。
- 除了 Boolean 和 Character 包装类是 extends Object 之外,其余的包装类都是 extends Number。
- 包装类的默认值为null。
public class WrapTestOne { public static void main(String[] args) { //装箱:把基本数据类型转换成包装类 //1、自动装箱 int t1=2; Integer t2=t1; //2、手动装箱 Integer t3=new Integer(t1); //测试 System.out.println("int类型变量t1="+t1); System.out.println("Integer类型对象t2="+t2); System.out.println("Integer类型对象t3="+t3); System.out.println("*************************"); //拆箱:把包装类转换成基本数据类型 //1、自动拆箱 int t4=t2; //2、手动拆箱 int t5=t2.intValue(); //测试 System.out.println("Integer类型对象t2="+t2); System.out.println("自动拆箱后,int类型变量t4="+t4); System.out.println("手动拆箱后,int类型变量t5="+t5); double t6=t2; System.out.println("自动拆箱后,double类型变量t6="+t6); t6=t2.doubleValue(); System.out.println("手动拆箱后,double类型变量t6="+t6); } } Console: int类型变量t1=2 Integer类型对象t2=2 Integer类型对象t3=2 ************************* Integer类型对象t2=2 自动拆箱后,int类型变量t4=2 手动拆箱后,int类型变量t5=2 自动拆箱后,double类型变量t6=2.0 手动拆箱后,double类型变量t6=2.0
public class WrapTestTwo { public static void main(String[] args) { //基本数据类型转换为字符串 int t1=2; String t2=Integer.toString(t1); //测试 System.out.println("int类型转换为String类型对象t2="+t2); System.out.println("********************************"); //字符串转换为基本数据类型 //1、包装类的parse int t3=Integer.parseInt(t2); //2、包装类的valueOf 先将字符串转换为包装类,再通过自动拆箱完成基本类型转换 int t4=Integer.valueOf(t2); //测试 System.out.println("String类型转换为int类型变量t3="+t3); System.out.println("String类型转换为int类型变量t4="+t4); } } Console: int类型转换为String类型对象t2=2 ******************************** String类型转换为int类型变量t3=2 String类型转换为int类型变量t4=2
public class WrapperTest { public static void main(String[] args) { Integer one=new Integer(100); Integer two=new Integer(100); System.out.println("one==two的结果:"+(one==two));//1 Integer three=100;//自动装箱 //等价于 Integer three=Integer.valueOf(100); System.out.println("three==100的结果:"+(three==100));//2 自动拆箱,相当于两个int基本数据类型在做比较 //Integer four=100; Integer four=Integer.valueOf(100); System.out.println("three==four的结果:"+(three==four));//3 Integer five=200; System.out.println("five==200的结果:"+(five==200));//4 Integer six=200; System.out.println("five==six的结果:"+(five==six));//5 Double d1=Double.valueOf(100); System.out.println("d1==100的结果:"+(d1==100)); // 除了 Float、Double 包装类,其它的都可以应用对象常量池概念。 Double d2=Double.valueOf(100); System.out.println("d1==d2的结果:"+(d1==d2)); } } Console: one==two的结果:false three==100的结果:true three==four的结果:true five==200的结果:true five==six的结果:false d1==100的结果:true d1==d2的结果:false
注意:Integer.valueOf() 方法原理如图(若不在该数值范围内,走实例化路线-->new)
(对于 Float、Double 包装类不适用这规则,其他包装类都可以应用对象常量池概念)