Java程序设计入门教程--装箱与拆箱

装箱和拆箱

        装箱时指把基本数据类型变为对应的封装过程,如将int 型封装为Integer对象类型,其他基本数据类型也可以封装成相对应的封装类。

        拆箱是指将封装类转变为对应的基本数据类型过程。如将Integer对象封装为int,其他封装类型也可以拆装成相对应的基本类型。

       装箱和拆箱可以分为手动装箱与拆箱和自动装箱与拆箱。

手动装箱与拆箱示例程序:

public class EnclosingTest {
    public static void main(String[] args) {
        //手动装箱
        int x=100;//定义一个基本数据类型变量x
        Integer in=new Integer(x);//将基本数据类型x封装为Integer对象类型
        System.out.println("封装类Integer类型in="+in);
        //手动拆箱
        Float f =new Float(3.14F); //将基本数据类型封装为Float类型
        float y=f.floatValue(); //将对象类型转换为基本数据类型float
        System.out.println("基本数据float类型y="+y);
    }
}

自动装箱与拆箱示例程序:

public class AutoEnclosingTest {
    public static void main(String[] args) {
        //自动装箱
        int x=100;	//定义基本数据类型变量x
        Integer in=x;	//将基本数据类型x直接封装为Integer对象类型
        System.out.println("封装类Integer类型in="+in);
        //自动拆箱
        Float f =new Float(3.14F);//将基本数据类型封装为Float类型
        float y=f;	//将对象类型直接赋给基本数据类型float
        System.out.println("基本数据float类型y="+y);
    }
}

 

猜你喜欢

转载自blog.csdn.net/u010764893/article/details/131022969