Boxing

测试自动装箱和自动拆箱,意思是运行的时候编译器帮我们加了两个代码;

public class AutoBoxingandUnBoxing {
    public static void main(String[]args){
        Integer a=1000;//jdk 5.0以后,有一个自动装箱:编译器帮我们改进代码:Integer a=new Integer(1000);
        //这里的a还是对象,把数赋给了对象;
        Integer b=2000;
        int c=new Integer(1500);//自动拆箱,编译器帮我们改进:new Integer(1500).intValue();把一个对象赋给了一个数;
        //但是这里的对象其实里面也是数,要不然会报错,不可能把对象里字符串赋给一个数;
        int d=b;//相当于b.intValue();
        System.out.println(d);
        
        Integer e=1234;
        Integer f=1234;
        System.out.println(e==f);//这里比较的是e和f两个对象;显然两个对象是不同的,所以输出的是false,因为地址不同;
        System.out.println(e.equals(f));//这里的equals方法比较的是e和f的值;所以输出true;
        Integer g=123;
        Integer h=123;
        System.out.println(g==h);//[-128,127]之间的数仍然会当作基本数据类型处理,为了提高效率!!
        System.out.println(g.equals(h));// 这里的两个输出的都应该是true;
    }
}
原文地址:https://www.cnblogs.com/myErebos/p/8586374.html