Autoboxing and Unboxing in Java

Sometimes, it is necessary to convert a basic data type such as int to an object. All basic types have a corresponding class. For example, the Integer class corresponds to the basic type int, which is usually called a wrapper class. (wrapper). Their names are very clear and direct corresponding to the basic data types. Integer, Long, Double,

Float, Short, Byte, Character, Void, Boolean. They are both final, so subclasses are not allowed to be defined.

Next look at the code:

package PrimaryTest;

import java.util.ArrayList;

public class autoboxing {
    public static void main(String[] args) {
        /**
         * We want to define an array list, and the data type in the angle brackets (generic) is not allowed to be a basic data type, that is to say, it cannot be written as
         * ArrayList<int> list In this way, we want to put the object type of int in it. This uses the Integer wrapper class. so
         * In angle brackets we write Integer
         */
        ArrayList<Integer> list = new ArrayList<>();
        /**
         * We directly added a content with the add method. Please note that we directly added a 3. If there is no automatic boxing, an error will be reported.
         With this automatic boxing mechanism, although we are executing list.add(3), it is actually automatically converted to list.add(Integer.valueOf(3));
         This transformation is called (autoboxing) autoboxing
         */
        list.add(3);

        System.out.println("---------------------this is the dividing line------------------- ------");
        /**
         * On the contrary, when we assign an Integer object to an int, it will automatically unbox and convert the Integer object to the basic data type of int
         */
        int n  = list.get(0);
        //actually execute int n = list.get(0).intValue();
        System.out.println(n); //The result is 3

        /**
         * Automatic boxing and unboxing even in arithmetic expressions, e.g.;
         */
         Integer a = 3 ;
         a++;
         System.out.println(a);
         //The compiler can automatically insert an unboxing instruction, and then after a self-increment calculation, the result is boxed again
    }
}

There is another benefit of using numeric object wrappers. JAVA designers have discovered that they can place certain basic methods in the wrappers, such as converting a numeric string into a numeric value. as follows:

    String abc  ="123";
        int aa = Integer.parseInt(abc);
        System.out.println(aa); //The result is 123
There is nothing to do with the Integer object here, parseInt is a static method, but the Integer class is a good place to put this method.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325626095&siteId=291194637