Basic type of automatic disassembly box

Automatic disassembly box

Basic data type

Basic type, also known as built-in type, is a special type different from class in Java, and it is also the type we use most frequently in the programming process.

Detailed introduction to basic data types: Basic (II): basic data type

Advantages of basic types

In Java, we can use the new keyword to create new objects. The newly created objects are stored in the heap. We use the corresponding objects through references in the stack. Therefore, the object itself is very resource consuming. Basic types are the most frequently used types in our programming process, such as int and boolean. If we use the new keyword to create new objects every time, it will be particularly cumbersome. Therefore, the basic data type came into being. The variables of this kind of data do not need to be created through the new keyword. They will not be created on the heap, but directly stored in the stack memory, so it will be more efficient.

Packaging type

The basic types in Java are not object-oriented, so it is very inconvenient to use them in practice. In order to solve this problem, Java provides corresponding classes for each basic data type. In this way, the class corresponding to the basic data type is called Wrapper Class.

All wrapper classes are in Java In Lang package, the correspondence between basic types and packaging classes is as follows:

Basic data type Packaging
byte Byte
boolean Boolean
short Short
char Character
int Integer
long Long
float Float
double Double

The packing class corresponding to the basic type does not need to be memorized. From the table, we can see that the packing class names of other basic data types except int and char are capitalized, so we only need to remember the two special characters of char and int, namely Character and Integer

Why packaging is needed

As mentioned in the previous advantages of basic types, Java provides eight basic data types to improve efficiency. Why do you need wrapper classes? As mentioned above, because the basic data type is not Object-oriented, it is very inconvenient in the actual use process. For example, when we use the collection, we cannot store the data of the basic data type into the collection, because the collection container requires that the elements must be of Object type.

In order to make the basic data type have the characteristics of object, packaging class appears. As the name suggests, packaging class is to "package" the basic data type to make it have the properties and characteristics of object, and add corresponding attributes and methods to facilitate the operation of basic type.

Unpacking and packing

Since the basic data types and wrapper classes correspond to each other, they can also be converted to each other.

The process of converting the basic data type into packaging class is packaging, which corresponds to boxing in English and boxing in Chinese

The process of converting a packaging class into a basic data type is to unpack, which corresponds to unpacking in English and unpacking in Chinese

In Java 1 Before 5, we can use the following code for packing operation:

	Integer i = new Integer(10);

Automatic unpacking and automatic packing

From Java 1 In version 5, Java provides the functions of automatic unpacking and automatic packing. Automatic here is the steps that need to be operated manually, which can be omitted, and the Java program will complete these operations automatically.

	Integer i = 10; // Automatic packing
	int a = i; 		// Automatic unpacking

Implementation principle

/**
 * Automatic packing is realized through the valueOf() method of the packing class
 * Automatic unpacking is realized through the xxxValue() method of the packing class object
 */
public class AutoBoxing {
    public static void main(String[] args) {
        Integer integer = 10; // Automatic packing, integer valueOf(10)
        int i = integer;      // Automatic unpacking, integer intValue()
    }
}

Usage scenario

Scenario 1: put basic types into collection
public class AutoBoxingTest {
    public static void main(String[] args) {
        /*
         * No error will be reported. Automatic packing will be carried out here,
         * List add(Integer.valueOf(i))
         */
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(i); 
        }
    }
}
Scenario 2: comparison between basic types and packaging types
/**
 * When comparing a package class with a basic type, the package class is unpacked into a basic data type before comparison
 */
public class AutoBoxingTest {
    public static void main(String[] args) {
        Integer i = 1;
        // i.intValue() == 1
        System.out.println(i == 1 ? "equal" : "not equal");
        Boolean bool = Boolean.TRUE;
        // bool.booleanValue()
        System.out.println(bool ? "true" : "false");
    }
}
Scenario 3: packing type operation
public class AutoBoxingTest {
    public static void main(String[] args) {
        /*
         * The operation between the two packing classes will be automatically unpacked as the basic type
         * Integer i = Integer.valueOf(10);
         * Integer j = Integer.valueOf(20);
         *
         * i + j => i.intValue() + j.intValue();
         */
        Integer i = 10, j = 20;
        System.out.println(i + j);
    }
}
Scenario 4: use of ternary operators
public class AutoBoxingTest {
    public static void main(String[] args) {
        /*
         * Integer i = Integer.valueOf(0);
         * When the operands of the ternary operator are wrapper objects and basic data types,
         * The objects will be automatically unpacked into basic data types for operation
         *
         * NPE occurs when the value of i is null
         */
        boolean flag = true;
        Integer i = 0;
        int j = 1;
        int k = flag ? i : j; // flag ? i.intValue() : j
    }
}
Scenario 5: function parameters and return values
public class AutoBoxingTest {
    /**
     * Automatic unpacking
     *
     * @param num Integer wrapper class object
     * @return Integer basic type literal
     */
    public int getNum1(Integer num) {
        return num;
    }

    /**
     * Automatic packing
     *
     * @param num Integer basic type literal
     * @return Integer wrapper class object
     */
    public Integer getNum2(int num) {
        return num;
    }
}

Automatic disassembly box and cache

public class AutoBoxingCache {
    public static void main(String[] args) {
        /*
         * In Java = = compares references to objects, while equals compares values
         * According to the conventional routine, the output of both comparisons should be false, but due to Java 5
         * A new function is introduced in the operation of Integer to save memory and improve performance
         * Integer objects are cached and reused by using the same object reference
         *
         * be careful:
         *    1,Applicable to integer value range: - 128 ~ 127
         *    2,Applies only to auto boxing, not to objects created using constructors
         */
        Integer integer1 = 10, integer2 = 10;
        System.out.println(integer1 == integer2 ? "true" : "false"); // true
        Integer integer3 = 200, integer4 = 200;
        System.out.println(integer3 == integer4 ? "true" : "false"); // false
    }
}

Problems caused by automatic disassembly and assembly of box

  • When comparing values of packaging objects, you cannot simply use = =. Although the number between - 128 and 127 is OK, values outside this range still need to be compared with equals
  • In some scenarios, automatic unpacking will be carried out. When the packing class object is null, NPE (null pointer exception) will be thrown during automatic unpacking
  • If there are a lot of disassembly and assembly operations in the cycle, a lot of resources will be wasted

Posted by xray_griff on Wed, 11 May 2022 04:11:12 +0300