4.1.6 自动装箱/自动拆箱

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6


1.概述

自动装箱把 基本类型 包装成对应的 包装类型 的过程例如
Integer a = 5;
其中a是引用类型引用了包装对象的地址。
编译器会完成对象的自动装箱其完整写法为Integer a = Integer.valueOf(5);

自动拆箱从包装类型的值自动转变为基本类型的值例如
int i = a;
其中a现在是包装类型没法给变量赋值需要把5取出来。
编译器会完成自动拆箱int i = a.intValue();

2.自动装箱与自动拆箱测试

package partThree;
/*本类用于测试自动装箱和自动拆箱*/
public class TestBox {
    public static void main(String[] args) {
        //1.定义包装类型的数据
        //回顾:以前创建包装类型的两种方式
        Integer i1 = new Integer(127);
        Integer i2 = Integer.valueOf(127);
        //2.现在的方式:
        /*1.自动装箱:编译器会自动把基本类型int 5,包装成包装类型Integer
         * 然后交给i3来保存,自动装箱底层发生的代码Integer.valueOf(5);
         * valueOf()的方向: int --> Integer*/
        Integer i3 = 5;//不会报错,这个现象就是自动装箱
        System.out.println(i3);
        /*2.自动拆箱:编译器会自动把包装类型的i1拆掉"箱子",变回基本类型数据127
         * 然后交给i4来保存,自动拆箱底层发生的代码:i1.intValue();
         * intValue()的方向:Integer -> int
         * */
        int i4 = i1;//不会报错,这个现象就是自动拆箱
        System.out.println(i4);
    }
}
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6