Boxing and unboxing in Java deep understanding of _java

Source: Internet
Author: User
Tags arithmetic numeric value static class wrapper

The problem of automatic boxing and unboxing is a cliché in Java, and today we'll take a look at some of the problems in boxing and unboxing. This article first about boxing and unpacking the most basic things, and then look at the interview written in the often encountered with the box, unpacking related issues.

A. What is boxing? What is a unpacking case?

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

Copy Code code as follows:

Integer i = new Integer (10);

The automatic boxing feature is provided from the Java SE5, and if you want to generate an integer with a value of 10, this is all you need to do:

Copy Code code as follows:

Integer i = 10;

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

So what is a unpacking? As the name suggests, the corresponding to the boxing, is to automatically convert the wrapper type to the basic data type:

Copy Code code as follows:

Integer i = 10; Packing
int n = i; Split Box

Simply put , boxing is the automatic conversion of the base data type to the wrapper type, and the unboxing automatically converts the wrapper type to the base data type.

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

Two. How to implement the boxing and unboxing

After the basic concept of boxing is understood in the previous section, this section is about how boxing and unboxing are implemented.

Let's take the Interger class for example, and look at the following code:

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:

From the bytecode content of the decompile, we can see that the integer valueof (int) method is automatically invoked when boxing. And in the unboxing of the automatic call is the integer Intvalue method.

Others are similar, such as Double, Character, do not believe that a friend can manually try it.

So you can summarize the process of boxing and unboxing in a word:

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

Three. Related questions in the interview

Although most people are aware of the concept of boxing and unpacking, they are not necessarily able to answer the question of packing and unpacking in interviews and written tests. The following is a list of common face 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 = m;
Integer i2 = m;
Integer i3 =;
Integer i4 =;
System.out.println (I1==I2);
System.out.println (I3==I4);

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


Why is there such a result? The output indicates that I1 and I2 point to the same object, while i3 and I4 point to different objects. At this point just a look at the source to know exactly, the following code is an integer valueof method of concrete implementation:

public static Integer valueof (int i) {
if (i >= -128 && i <= integercache.high) return
Integercache . cache[i + 128];
else return the
new Integer (i);

And the implementation of the Integercache class is:

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

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

The I1 and I2 values in the above code are 100, so that the existing objects are taken directly from the cache, so i1 and I2 point to the same object, and 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 problem is the same, but in fact it is not. The actual output results are:


For specific reasons, readers can look at the implementation of the valueof of the double class.

Here only explains why the valueof method of the double class uses a different implementation than the ValueOf method of the integer class. It's simple: the number of integer values within a range is limited, but the floating-point numbers are not.

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

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

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

The output results are:


As for why this is the result, similarly, see the Boolean class source will also be 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 results of the above output is true.

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

Of course, this topic belongs to a relatively broad category. But the main point must be answered, I conclude that there are mainly the following two differences:

1 The first method does not trigger the process of automatic boxing, and the second method triggers;

2 The difference between the efficiency of execution and the utilization of resources. The execution efficiency and resource footprint of the second approach are better than the first case in general (note that this is not absolute).

5. What is the output 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));

Don't look at the output, the reader will think about what the output of this piece of code is. What you should note here is that when the two operands of the "= =" operator are all references to the wrapper type, is whether the comparison points to the same object, and if one of the operands is an expression (that is, it contains an arithmetic operation), the comparison is a numeric value (that is, the process that triggers the automatic unboxing). In addition, for wrapper types, the Equals method does not convert to type. Understand these 2 points, the above output will be clear at a glance:


There is no doubt about the first and second output results. The third sentence because a+b contains arithmetic operations, the automatic unboxing process is triggered (the Intvalue method is called), 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 first call the Intvalue method, after the addition of the value of the operation, then call the Integer.valueof method, and then the equals comparison. The same is true for the latter, but note the result of the second and last output (if the value is of type int, the boxing procedure calls the integer.valueof; if it is a long type, the Long.valueof method of the boxing call).

The above is a small set to introduce the Java in the boxed and unboxing of in-depth understanding, hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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: 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.