In-depth analysis of boxing and unboxing in Java

Source: Internet
Author: User
Tags arithmetic

Tag: Lin body take counter order show byte floating point LSP JVM

The following is the directory outline for this article:

A. What is boxing? What is 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.

Two. How the packing and unpacking is achieved

1: Anti-compilation class file: Javap-c class name

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

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

Three. Questions related to the interview

1: TheValueOf method is used during the boxing process when Integer a=1, there is a static inner class Integercache in integer.valueof (), there is a constant cache[], That is, the integer Chang (in fact, the buffer pool technology, the use of space-time policy, also known as the Object pool), in the Chang (Object Pool) integer has been created by default, the value "128-127" of the integer cache data. So when you use an integer a=1, the JVM will directly find a reference to that value in the object pool . That is, when an integer object is declared in this way, the JVM first looks for an object with a value of 1 in the cache pool of the integer object, if there is a reference to return the object directly, and if not, uses the new Integer (new in the JVM heap) creates an object and returns a reference address for the object.

Note: The maximum value of 127 can be modified by the JVM's startup parameters-xx:autoboxcachemax=size

2:int is automatically boxed when compared to integer

  

3: Talk about the integer i = new integer (XXX) and the integer I =xxx;

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 way of performing efficiency and resource occupancy is better than the first case in general, where the value is not between (-128-127) (note that this is not absolute).

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:

1 Integer i = newInteger(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:

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

12 Integer i = 10;  //装箱intn = i;   //拆箱

  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:

1234567 public  class  < Code class= "Java plain" >main { &NBSP;&NBSP;&NBSP;&NBSP; public  static   void  main (string[] args) { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;            integer i =  10 ; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; int  n = i; &NBSP;&NBSP;&NBSP;&NBSP; } }

 After you decompile the class file, you get the following: Javap-c class name

  

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. First, look at the question, for the four variables defined below = = comparison:

123456 Integer a=1; Integer b=1; Integer c=n; Integer d=n; System. Out. println(a= =b); True System. Out. println(c= =d); False

We all know that = = is a comparison object reference in Java and returns true if two object references point to the same piece of memory in the heap, otherwise false. According to the automatic boxing rules we know that integer a = 1 <==> integer a = integer.valueof (1), but on the ValueOf method, view the source code:

1234567 public static Integer valueOf(int i) { final int offset = n;     if (i >= -128 && i <=< Span class= "crayon-h" > 127) { //must cache return integercache. Cache[i + offset];     } return new Integer(i); }

Integer.valueof () has an inner class integercache (similar to a constant array, also called an object pool) that maintains an integer array cache with a length of (128+127+1) = 256. There is also a static block in the integer class

1234 static {         for (int i Span class= "Crayon-o" >= 0; i < cache. Length; i++) Cache[i] = new Integer(i - ; }

As you can see from this static block, the integer cache data for the value "128-127" has been created by default. So when you use an integer a=1, the JVM will directly find a reference to that value in the object pool. That is, when an integer object is declared in this way, the JVM first looks for an object with a value of 1 in the cache pool of the integer object, if there is a reference to return the object directly, and if not, creates an object with the new integer and returns the reference address of the object. Because java = = Compares two objects for the same reference (that is, compares memory addresses), both A and B are references to the same object, so the a==b result of True;c and D has exceeded the cached range, so the integer object is regenerated, so the c==d result is false.

2. What is the output of the following code?

123456789101112 publicclassMain {    publicstaticvoidmain(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:

False false

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.

Let's do a collation:
The integer faction: integer, Short, Byte, Character, long are similar to the implementations of the valueof methods of these classes.
Double factions: the implementation of the ValueOf method of double and float is similar. each time a different object is returned.

The following is a summary of the integer factions, such as:

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?

123456789101112131415161718192021 publicclassMain {    publicstaticvoidmain(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, let the reader think about what the output of this code is. It is important to note that when the two operands of the "= =" operator are references to the wrapper type, it is whether the comparison points to the same object, 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:

True
False
True
True
True
False
True

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

If you have questions about the specific execution process above, you can try to get the anti-compiled bytecode content for viewing.

In-depth analysis of boxing and unboxing 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.