16-11-packaging of Java common classes [dry goods notes]

Posted by proxydude on Mon, 10 Jan 2022 21:14:01 +0100

1. Packaging

java.lang package. Basic data types are easy to use and efficient. But there is no corresponding method to operate it. Use a class to wrap the basic type data. This class is called the wrapper class. The wrapper class defines methods for manipulating basic type data.

1.1. Package type corresponding to basic data type (java.lang package):

int (4 bytes)Integer
Byte (1 byte)Byte
short (2 bytes)Short
long (8 bytes)Long
float (4 bytes)Float
double (8 bytes)Double
char (2 bytes)Character
boolean (1 byte)Boolean

2. Packing / unpacking

The process of back and forth conversion between the basic type and the corresponding packing class object is called "packing" and "unpacking"

  • Packing: convert from basic type to corresponding packing class object;
  • Unpacking: convert from packing class object to corresponding basic type.

Base value -- > wrapper object

  • Construction method: Integer i = new Integer(3);
  • Static method: integer I = integer valueOf(3);

Wrapper object -- > base value

  • Member method: int num = i.intValue();

3. Automatic packing / unpacking

  • Automatic packing

Automatically convert the basic data type to the wrapper type.
At jdk1 Before 5, if you want to generate an Integer object with a value of 10, you must do this:

Integer i = new Integer(10);

And from jdk1 5 provides the feature of automatic packing from the beginning. If you want to generate an Integer object with a value of 10, you only need to do this:

Integer i = 10;

In this process, the corresponding Integer object will be automatically created according to the value, which is boxing.

  • Automatic unpacking

Automatically convert the wrapper type to the basic data type.

Integer i = 10;  //Packing
int n = i;   //Unpacking
  • Realization of packing and unpacking
public class Main {
    public static void main(String[] args) {
        Integer i = 10; // Automatic packing
        int n = i; // Automatic unpacking
    }
}

When boxing, the valueOf(int) method of Integer is called automatically. The intValue method of Integer is called automatically when unpacking.
The boxing process is realized by calling the valueOf method of the wrapper type, while the unpacking process is realized by calling the xxxValue method of the wrapper. (xxx represents the corresponding basic data type).

4. Conversion between basic type and string

  • Basic type -- > string
    1. Value of basic data type + "";
    2. Static method of wrapper class: static String toString(int i)
    3. Static method of String class: static String valueOf(int i)
  • String -- > basic type: all wrapper classes except Character class have parseXxx() static method, which can convert string parameters to corresponding basic types
    1. public static byte parseByte(String s): converts a string parameter to the corresponding byte basic type.
    2. public static short parseShort(String s): converts a string parameter to the corresponding short basic type.
    3. public static int parseInt(String s): converts a string parameter to the corresponding int basic type.
    4. public static long parseLong(String s): converts a string parameter to the corresponding long basic type.
    5. public static float parseFloat(String s) converts a string parameter to the corresponding float basic type.
    6. public static double parseDouble(String s): converts a string parameter to the corresponding double basic type.
    7. public static boolean parseBoolean(String s): converts a string parameter to the corresponding boolean basic type.
public static void main(String[] args) {
    int i = Integer.parseInt("99");
    System.out.println(i);
    // Note: if the content of the string parameter cannot be correctly converted to the corresponding basic type, Java. Java. XML will be thrown Lang.numberformatexception exception.
}

5. Interview related

5.1. What is the output result of the following code?

public class Main{
    public static void main(String[] args) {
         
        Integer i1 = 100;
        Integer i2 = 100;
        Integer i3 = 200;
        Integer i4 = 200;
         
        System.out.println(i1==i2); // true
        System.out.println(i3==i4); // false
    }
}

The output shows that i1 and i2 point to the same object, while i3 and i4 point to different objects. The specific source code implementation of the valueOf method of Integer:

public static Integer valueOf(int i) {
    if(i >= -128 && i <= IntegerCache.high)
        return IntegerCache.cache[i + 128];
    else
        return new Integer(i);
}

The implementation of IntegerCache class is:

private static class IntegerCache {
    static final int high;
    static final Integer cache[];

    static {
        final int low = -128;

        // high value may be configured by property
        int h = 127;
        if (integerCacheHighPropValue != null) {
            // Use Long.decode here to avoid invoking methods that
            // require Integer's autoboxing cache to be initialized
            int i = Long.decode(integerCacheHighPropValue).intValue();
            i = Math.max(i, 127);
            // Maximum array size is Integer.MAX_VALUE
            h = Math.min(i, Integer.MAX_VALUE - -low);
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);
    }

    private IntegerCache() {}
}

It can be seen from these two codes that when creating an Integer object through the valueOf method, if the value is between [- 128127], it will return to point to integercache References to objects that already exist in the cache; Otherwise, create a new Integer object.
In the above code, the values of i1 and i2 are 100, so existing objects will be fetched directly from the cache, so i1 and i2 point to the same object, while i3 and i4 point to different objects respectively.

5.2. What is the output result of the following code?

public class Main {
    public static void main(String[] args) {
         
        Double i1 = 100.0;
        Double i2 = 100.0;
        Double i3 = 200.0;
        Double i4 = 200.0;
         
        System.out.println(i1==i2); // false
        System.out.println(i3==i4); // false
    }
}

The valueOf method of Double class will adopt a different implementation from the valueOf method of Integer class. It's simple: the number of Integer values in a range is limited, but floating-point numbers are not.
[note] the implementation of valueOf methods of Integer, Short, Byte, Character and Long is similar.
The implementation of the valueOf method of Double and Float is similar.

5.3. What is the output result of the following code?

public class Main {
    public static void main(String[] args) {
         
        Boolean i1 = false;
        Boolean i2 = false;
        Boolean i3 = true;
        Boolean i4 = true;
         
        System.out.println(i1==i2); // true
        System.out.println(i3==i4); // true
    }
}

Specific implementation of Boolean valueOf method:

public static Boolean valueOf(boolean b) {
    return (b ? TRUE : FALSE);
}

And what are TRUE and FALSE? Two static member properties are defined in Boolean:

 public static final Boolean TRUE = new Boolean(true);

    /** 
     * The <code>Boolean</code> object corresponding to the primitive 
     * value <code>false</code>. 
     */
    public static final Boolean FALSE = new Boolean(false);

5.4. Talk about Integer i = new Integer(xxx) and Integer i =xxx; The difference between the two ways.

Of course, this topic belongs to a relatively broad type. However, the key points must be answered. I summarize the following two differences:
1) The first method will not trigger the automatic packing process; The second method will trigger;
2) Differences in execution efficiency and resource occupation. In general, the execution efficiency and resource occupation of the second method are better than those of the first (note that this is not absolute).

5.5 what is the output result of the following program?

public class Main {
    public static void main(String[] args) {
         
        Integer a = 1;
        Integer b = 2;
        Integer c = 3;
        Integer d = 3;
        Integer e = 321;
        Integer f = 321;
        Long g = 3L;
        Long h = 2L;
         
        System.out.println(c==d); // true
        System.out.println(e==f); // false
        System.out.println(c==(a+b)); // true
        System.out.println(c.equals(a+b)); // true
        System.out.println(g==(a+b)); // true
        System.out.println(g.equals(a+b)); // false
        System.out.println(g.equals(a+h)); // true
    }
}

[note]

  1. When both operands of the "= =" operator are references of wrapper type, it is used to compare whether they point to the same object;
  2. If one of the operands is an expression (that is, it contains arithmetic operations), the value is compared (that is, it will trigger the process of automatic unpacking);
  3. For wrapper types, the equals method does not type cast.

The results of the penultimate and last output (if the value is of type int, the boxing procedure calls Integer.valueOf; if it is of type long, the boxing procedure calls the Long.valueOf method).

Thank you for your attention!
Your likes, comments, concerns and collections are the greatest encouragement to bloggers!
Keep updating JavaSE learning notes! Welcome to the column!

Related content
👉 JavaSE detailed notes column
👉 16-1-Scanner of common Java classes [dry goods note]
👉 16-2-Random [dry goods note] of common Java classes
👉 16-3-ArrayList of common Java classes [dry goods note]
👉 16-4-String of common Java classes [dry goods note]

Highlights of previous periods
👉 Process control in Java [dry goods note]
👉 Array in Java [dry goods note]
👉 Java classes and objects [dry goods note]
👉 Java written test question column

Topics: Java Back-end Interview Programmer