In-depth parsing of boxing and unpacking in Java

Source: Internet
Author: User

Automatic boxing and unpacking is a commonplace problem in Java, so let's take a look at some of the problems in boxing and unpacking today. This article first tells about boxing and unpacking the most basic things, and then look at the interview in the written test often encountered with the packing, unpacking related problems.

The following is the directory outline for this article:

A. What is boxing? What is unpacking?

Two. How the packing and unpacking is achieved

Three. Questions related to the interview

If there are any shortcomings, please understand and criticize, I appreciate it.

A. What is boxing? What is unpacking?

As mentioned in the previous article, Java provides a wrapper type for each of the basic data types, as for why the wrapper type for each of the basic data types is not elaborated here, and interested friends can access the relevant information. Before Java SE5, if you want to generate an integer object with a numeric value of 10, you must do this:

Integer i = new Integer (10);

The auto-boxing feature is provided at the beginning of Java SE5, if you want to generate an integer object with a numeric value of 10, this is all you need:
Integer i = 10;

This process automatically creates the corresponding integer object based on the value, which is the boxing.

So what is unpacking? As the name implies, it corresponds to boxing, which is to automatically convert the wrapper type to the basic data type:

Integer i = ten;  Boxing int n = i;   Unpacking

Simply put, boxing is the automatic conversion of the base data type to the wrapper type; unpacking is the automatic conversion of the wrapper type to the base data type.

The following table is the wrapper type for the base data type:

Int (4 bytes) Integer
Byte (1 bytes) Byte
Short (2 bytes) Short
Long (8 bytes) Long
Float (4 bytes) Float
Double (8 bytes) Double
Char (2 bytes) Character
Boolean (Undecided) Boolean
Two. How the packing and unpacking is achieved

In the previous section, after understanding the basic concept of boxing, this section examines how boxing and unpacking are implemented.

Let's take the Interger class as an example and look at the code below:

public class Main {public    static void Main (string[] args) {                 Integer i = ten;        int n = i;    }}

After you decompile the class file, you get the following:

  

The content of the bytecode obtained from the decompile can be seen as an integer valueof (int) method that is automatically called when boxing. The Intvalue method of integer is called automatically when unpacking.

Other similar, such as Double, Character, do not believe that friends can manually try.

So you can summarize the process of packing and unpacking in a sentence:

The boxing process is implemented by calling the wrapper's ValueOf method, and the unboxing process is implemented by invoking the wrapper's Xxxvalue method. (XXX represents the corresponding basic data type).

Three. Questions related to the interview

While most people are clear about the concept of boxing and unpacking, the question of packing and unpacking in interviews and written tests does not necessarily answer. Here are some common questions related to packing/unpacking.

1. What is the output of the following code?

public class Main {public    static void Main (string[] args) {                 Integer i1 = +;        Integer i2 = +;        Integer i3 = n;        Integer i4 = n;                 System.out.println (I1==I2);        System.out.println (I3==I4);    }}

Maybe some friends will say it will output false, or some friends will say that it will output true. But in fact the output is:

TrueFalse

Why do you have such a result? The output shows that I1 and I2 point to the same object, while i3 and I4 point to different objects. At this point only a look at the source code will know, the following is an integer valueof method of the specific implementation:

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

Where the Integercache class is implemented as:

private static class Integercache {        static final int high;        Static final Integer cache[];        static {            final int low = -128;            High value is configured by property            int h = 127;            if (integercachehighpropvalue! = null) {                //use Long.decode. 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 () {}    }

As you can see from these 2 pieces of code, when you create an integer object by using the ValueOf method, if the value is between [-128,127], a reference to the object that already exists in Integercache.cache is returned, otherwise a new integer object is created.

The values for I1 and I2 in the above code are 100, so the objects that already exist are taken directly from the cache, so i1 and I2 point to the same object, while i3 and I4 point to different objects respectively.

2. What is the output 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);        System.out.println (I3==I4);    }}

Some friends may think that the output of the above topic is the same, but in fact it is not. The actual output results are:
Falsefalse

As for the specific why, the reader can go to see the valueof of the double class.

This explains why the valueof method of the double class takes on a different implementation than the ValueOf method of the integer class. It is simple: the number of integer values in a range is limited, but floating-point numbers are not.

  Note that the implementations of the valueof methods of the classes Integer, short, Byte, Character, long are similar.

The implementation of the valueof method of Double and float is similar.

3. What is the result of this code output:

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);        System.out.println (I3==I4);    }}

The output is:

Truetrue

As to why this is the result, similarly, the source code of the Boolean class will be seen at a glance. The following is a specific implementation of the Boolean valueof method:

public static Boolean valueOf (Boolean b) {        return (b? True:false);    }
And what is TRUE and false? 2 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);

At this point, you should understand why the above output is true.

4. Talk about the integer i = new integer (XXX) and integer i =xxx, the difference between the two ways.

Of course, this topic belongs to a relatively broad category. But the main point must be answered, I summed up the following two points are the difference:

1) The first way does not trigger the automatic boxing process, while the second method will trigger;

2) difference in execution efficiency and resource occupancy. The second approach is more efficient and resource-intensive than the first case in general (note that this is not absolute).

5. What are the output results 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);        System.out.println (e==f);        System.out.println (c== (a+b));        System.out.println (C.equals (a+b));        System.out.println (g== (a+b));        System.out.println (G.equals (a+b));        System.out.println (G.equals (A+h));}    }
Readers think about what the output of this piece of code is. It is important to note that:when the two operand of the "= =" operator is a reference to the wrapper type, the comparison points to whether the same object is the same, and if one of the operands is an expression (that is, the arithmetic operation is included), the value is compared (that is, the process that triggers the automatic unboxing). Also, for wrapper types, the Equals method does not convert the type. Once you understand these 2 points, the above output will be at a glance:
Truefalsetruetruetruefalsetrue
The first and second outputs have no doubt. The third sentence because a+b contains arithmetic operations, it triggers the automatic unboxing process (which calls the Intvalue method), so they compare the values for equality. And for C.equals (A+B) will trigger the automatic unpacking process, and then trigger the automatic boxing process, that is a+b, will call the Intvalue method, the addition operation after the value, then call the Integer.valueof method, then the equals comparison. The same is true for the latter, but pay attention to the result of the second and last output (if the value is of type int, the boxing procedure calls integer.valueof; if it is a long type, the Long.valueof method of the boxing call).

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

In-depth parsing of boxing and unpacking in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.