Reprint: Detailed explanation of the implementation principle of Java automatic packing and unpacking

Source: Internet
Author: User

Original: http://www.jb51.net/article/111847.htm

What is auto-boxing and unpacking

Automatic boxing is that Java automatically converts the original type values into corresponding objects, such as converting an int variable to an integer object, a process called boxing, which translates an integer object into an int type value, which is called unpacking. Because the boxes and unboxing here are automatically non-human for conversion, it is called as automatic packing and unpacking. Primitive type Byte, short, char, int, long, float, double, and Boolean corresponding wrapper classes are byte, short, Character, Integer, long, float, double, Boo Lean

The following example is the confusion caused by automatic boxing and unpacking

  public class Test {public     static void Main (string[] args) {         Test ();     }     public static void Test () {       int i = +;       int i0 = +;       Integer i1 = +;       Integer i2 = +;       Integer i3 = 0;       Integer i4 = new Integer (+);       Integer i5 = new Integer (+);       Integer I6 = new Integer (0);       Double d1=1.0;       Double d2=1.0;       System.out.println ("i=i0\t" + (i = = I0));       System.out.println ("i1=i2\t" + (I1 = = I2));       System.out.println ("i1=i2+i3\t" + (I1 = = i2 + i3));       System.out.println ("i4=i5\t" + (i4 = = i5));       System.out.println ("i4=i5+i6\t" + (I4 = = i5 + I6));         System.out.println ("d1=d2\t" + (D1==D2));        System.out.println ();         }   }

Would you like to see the following output as you expected?

Results of the output:

I=i0 true
I1=i2? True
I1=i2+i3?? True
I4=i5? False
I4=i5+i6?? True
D1=d2 false

Why is that? Continue to look down with doubt.

The principle of automatic boxing and unpacking

When the compiler calls valueof to convert the original type value to an object while auto-boxing, the compiler converts the object to the original type value by calling methods such as Intvalue (), Doublevalue (), and so on when the box is automatically disassembled.

Understanding the principle of automatic packing and unpacking, we take the above questions to analyze the automatic boxed implementation of the source code. As follows:

  public static Integer valueOf (int i) {//Determines whether I is between 128 and 127, and if not, gets an instance of the wrapper class from Integercache. Otherwise new instance if (I >= integercache.low && i <= integercache.high) return integercache.cache[i + (-inte    Gercache.low)];  return new Integer (i); }//Use Hengyuan mode to reduce the creation of objects (Hengyuan design mode It is necessary to understand, I think is the simplest design pattern, perhaps we often use in the project, do not know his name only) private static class Integercache {static F    inal int low =-128;    static final int high;    Static final Integer cache[];      Static methods, when classes are loaded, are initialized cache[], static variables are stored in the constant pool static {//high value is configured by property int h = 127;      String Integercachehighpropvalue = Sun.misc.VM.getSavedProperty ("Java.lang.Integer.IntegerCache.high");          if (integercachehighpropvalue! = null) {try {int i = parseint (Integercachehighpropvalue);          i = Math.max (i, 127);        Maximum array size is integer.max_value h = math.min (i, Integer.max_value-(-low)-1);     } catch (NumberFormatException nfe) {     If The property cannot is parsed into an int, ignore it.      }} high = h;      cache = new Integer[(high-low) + 1];      int j = Low;      for (int k = 0; k < cache.length; k++) cache[k] = new Integer (j + +);    range [ -128, 127] must be interned (JLS7 5.1.7) assert Integercache.high >= 127; } private Integercache () {}}

Integer I1 = 40; Automatic boxing, equivalent to calling the Integer.valueof (40) method.

First determine whether the I value between 128 and 127, if between-128 and 127 is directly from the Integercache.cache cache to obtain the specified number of wrapper class;

The Integercache internally implements an integer static constant array that, when the class is loaded, executes the static block initialization-an integer object between 128 and 127, stored in the cache array. The cache is a constant and is stored in the Java method area.

Then look at the following is the java8 of the basic types of automatic boxing code implementation. As follows:

  The Boolean native type is automatically boxed into a Boolean public static Boolean ValueOf (Boolean b) {return (b?  True:false);    }//byte native type automatically boxed into a byte public static byte ValueOf (Byte b) {final int offset = 128;  return bytecache.cache[(int) b + offset];    }//byte native type automatically boxed into byte public static short valueOf (short s) {final int offset = 128;    int sasint = s;    if (sasint >= -128 && sasint <= 127) {//must cache return Shortcache.cache[sasint + offset];  } return new short (s); }//char native type automatically boxed into Character public static Character valueOf (char c) {if (c <= 127) {//must cache return Cha    ractercache.cache[(int) c];  } return new Character (c); }//int native type automatically boxed into an integer public static integer valueOf (int i) {if (I >= integercache.low && i <= intege    Rcache.high) return integercache.cache[i + (-integercache.low)];  return new Integer (i);    }//int native type automatically boxed into long public static long valueOf (long L) {final int offset = 128; if (l >=-128 && L <= 127) {//would cache return longcache.cache[(int) L + offset];  } return new Long (L);  }//double native type is automatically boxed into double public static double valueOf (double D) {return new double (d);  }//float native type automatically boxed into float public static float valueOf (float f) {return new Float (f); }

Through the analysis of source discovery, only double and float automatic boxing code does not use the cache, each time is new object, the other 6 basic types have used the cache policy.

The caching policy is used because the cached objects are often used (such as characters, numbers between 128 and 127) to prevent each auto-boxing from creating an instance of this object.

While double, float is floating point type, there is no special hot (often used) data, the cache effect is not a few other types of use of high efficiency.

Below is a look at the packing and unpacking problems.

  1, this does not explain is true  System.out.println ("i=i0\t" + (i = = I0));//true  //2, int value as long as the auto-boxing object between 128 and 127 is obtained from the cache, So for true  System.out.println ("i1=i2\t" + (I1 = = I2)),//true  //3, when it comes to the calculation of numbers, you must first disassemble the box into int and do the addition operation, So regardless of whether their value is between 128 and 127, as long as the number is the same as true  System.out.println ("i1=i2+i3\t" + (I1 = = i2 + i3));//true   //compares the object memory address, So for false  System.out.println ("i4=i5\t" + (i4 = = i5)),//false  //5, with the 3rd interpretation, unpacking to do the addition operation, the comparison is the number, so true  System.out.println ("i4=i5+i6\t" + (I4 = = i5 + I6));     the boxing operation of//true//double does not use the cache, each time it is a new Double, so false  System.out.println ("d1=d2\t" + (D1==D2));//false

Believe you see this should be able to understand the above program output results Why is true,false, as long as the master principle, similar problems are solved, I hope that everyone's learning has helped, but also hope that we support the script home.

Reprint: The implementation principle of Java automatic boxing and unpacking

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.