Java-unboxing and boxing

table of Contents

Boxing

Unboxing

Code display

Automatic unboxing and packing

Code display


Boxing

Packing definition: Pack basic types of data into packaging classes. (Basic types of data -> packaging)

Basic data types (four types and eight types)

          Integer: byte/short/int/long

          Floating point: float/double

          Character type: char

          Boolean: boolean

[1] Construction method:    

         ①Integer(int value): Construct a newly allocated Integer object, which represents the specified int value.  

         ②Integer(String s): Construct a newly allocated Integer object, which represents the int value indicated by the String parameter.              

The passed string must be a basic class

[2] Static method:

        ① static Integer valueOf(int i): returns an Integer instance representing the specified int value.  

        ② static Integer valueOf(String s): Returns the Integer object that holds the value of the specified String.

Unboxing

Unpacking overview : Take out the basic types of data in the packaging class (Packaging class -> basic type data)

Member method : int intValue(): returns the value of this Integer in int type.

Code display

public class Demo01Integer {
    public static void main(String[] args) {
        //装箱:把基本类型的数据,包装到包装类中。(基本类型的数据->包装类)
       
        //构造方法
        Integer in1=new Integer(1);
        //1 重写了toString方法
        System.out.println(in1);

        Integer in2=new Integer("1");
        //1
        System.out.println(in2);

        //静态方法
        Integer in3=Integer.valueOf(1);
        System.out.println(in3);

        Integer in4=Integer.valueOf("1");
        //Integer in4=Integer.valueOf("a");   //NumberFormatException 数字格式化异常
        System.out.println(in4);
        
        //拆箱:在包装类中取出基本类型的数据(包装类->基本类型的数据)
        int i=in1.intValue();
        System.out.println(i);
    }
}

Automatic unboxing and packing

Definition of automatic boxing and automatic unboxing: Since we often have to convert between basic types and packaging classes, starting from Java 5 (JDK 1.5), the boxing and unboxing actions of basic types and packaging classes can be completed automatically.

Code display

public class Demo02Auto {
    public static void main(String[] args) {

        //自动装箱:直接把int类型的整数赋值给包装类
        //自动装箱。相当于Integer i = Integer.valueOf(4);或者是Integer i=new Integer(1);
        Integer i=4;

        //自动拆箱
        //等号右边:i是包装类,无法直接参与运算,将i对象转成基本数值(自动拆箱)i.intValue() + 5;
        i=i+5;
        //加法运算完成后,再次装箱,把基本数值转成Integer对象。
        
        //ArrayList集合无法直接存储整数,可以存储Integer包装类
        ArrayList<Integer> list=new ArrayList<>();
        //自动装箱  list.add(new Integer(1));
        list.add(1);
        //自动拆箱  list.get(0).intValue();
        int a=list.get(0);
    }
}

  

Guess you like

Origin blog.csdn.net/wtt15100/article/details/108210201