Java Programming Introductory Tutorial--Boxing and Unboxing

Boxing and unboxing

        Boxing refers to the process of converting basic data types into corresponding encapsulation processes, such as encapsulating int type into Integer object type, and other basic data types can also be encapsulated into corresponding encapsulation classes.

        Unboxing refers to the process of converting an encapsulation class into a corresponding basic data type. For example, if an Integer object is encapsulated as an int , other encapsulation types can also be disassembled into corresponding basic types.

       Boxing and unboxing can be divided into manual boxing and unboxing and automatic boxing and unboxing.

Sample program for manual boxing and unboxing:

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);
    }
}

Autoboxing and unboxing sample program:

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);
    }
}

 

 

Guess you like

Origin blog.csdn.net/u010764893/article/details/131022969