Java Auto Boxing and unpacking those things

Source: Internet
Author: User

Basic data types for 1.JAVA

In Java, data types can be divided into two major types, Primitive type (base type) and reference type (reference type). The value of the base type is not an object, and methods such as ToString (), Hashcode (), GetClass (), Equals () of the object cannot be called. So Java provides a wrapper type for each of the basic types. As follows:

Java basic data Types
INDEX Basic type Size Range of values Default value Package Type
1 Boolean --- True,false False Boolean
2 Byte 8bit -2^7--2^7-1 0 Byte
3 Char 16bit
\u0000-\UFFFF
\u0000 Character
4 Short 16bit -2^15--2^15-1 0 Short
5 Int 32bit -2^31--2^31-1 0 Integer
6 Long 64bit -2^63--2^63-1 0 Long
7 Float 32bit IEEE 754 0.0f Float
8 Double 64bit IEEE 754 0.0d Double

2. Talking about unpacking and packing

Boxing is a variable that assigns an original data type to the corresponding encapsulated class. Unpacking is a variable that assigns a wrapper class variable to the corresponding primitive data type.

The automatic boxing and unpacking mechanism is introduced in Java 1.5:

(1) Auto-Boxing: The basic types are wrapped with their corresponding reference types, so that they have the characteristics of the object, you can call ToString (), Hashcode (), GetClass (), Equals () and other methods.

As follows:

Integer a=3;//This is auto-boxing

In fact, the compiler calls the static integer valueOf (int i) method, valueOf (int i) returns an Integer object representing the specified int value, then it becomes this:

Integer a=3; = = Integer a=integer.valueof (3);

  1. Public static Integer valueOf (inti) {
  2. if (i >=-&&i <=integercache.high)
  3. //If I is between -128~high, the integer object of i is removed directly from the cache
  4. return integercache.cache[i + 128];
  5. Else
  6. return new Integer (i); //Otherwise it is created in heap memory
  7. }

(2) Unpacking: In contrast to automatic boxing, objects of reference types such as integers and double are re-simplified to the basic type of data.

As follows:

int i = new Integer (2);//This is unpacking.

The compiler internally calls Int intvalue () to return the int value of the integer object

    1. public int intvalue () {
    2. return value;
    3. }

Note: Automatic boxing and unpacking is done by the compiler, and the compiler determines whether boxing and unboxing are performed at compile time based on syntax.

Java definition: When automatic boxing for values from –128 to 127, they are boxed into an integer object, there will be reuse in memory, there is always only one object
If the value from –128 to 127 is exceeded, the boxed integer object is not reused, which is equivalent to creating an integer object each time it is boxed;

    1. Integer i1=100;
    2. Integer i2=100;
    3. Integer i3=300;
    4. Integer i4=300;
    5. System.out.println (I1==I2);
    6. System.out.println (I3==I4);

Run the result as "System." out. println (I1==I2); " is true, but "System." out. println (I3==I4); " to False. This means that I1 and I2 refer to the same object for the two integer references, while i3 and I4 point to different objects. Why is it? Is it not all called the integer.valueof (int i) method?

  1. Public static Integer valueOf (inti) {
  2. if (i >=-&&i <=integercache.high)
  3. //If I is between -128~high, the integer object of i is removed directly from the cache
  4. return integercache.cache[i + 128];
  5. Else
  6. return new Integer (i); //Otherwise it is created in heap memory
  7. }

We can see that when i>=-128 and I<=integercache.high, the Integercache is returned directly. Cache [i + 128]. Where Integercache is an integer internal static class with the original code as follows:

  1. Private Static class Integercache {//inner class, note that its properties are defined as static final
  2. static final Inthigh; //cache upper bound
  3. static final Integer cache[]; Cache caching is an array that holds an integer type
  4. Static {//statement block
  5. final int low =-; Cache lower bound, value immutable
  6. //High value could beconfigured by property
  7. int h = 127; H value, which can be adjusted by setting the Autoboxcachemax parameter of the JDK (see (3))
  8. if (integercachehighpropvalue! =null) {
  9. //Use Long.decode This avoid invoking methods that
  10. //Require Integer ' s autoboxing cache to be initialized
  11. //By decoding Integercachehighpropvalue, and getting a candidate upper bound value
  12. int i = Long.decode (integercachehighpropvalue). Intvalue ();
  13. //Take a larger upper bound, but not greater than the integer boundary max_value
  14. i = Math.max (i, 127); Upper bound minimum is 127
  15. //Maximum array size is Integer.max_value
  16. h = math.min (i, Integer.max_value--low);
  17. }
  18. High = h; //Upper bounds OK, at this time high default is generally 127
  19. //Create cache block, note cache array size
  20. cache =New integer[(high-low) + 1];
  21. int j = Low;
  22. For (int k = 0; k <cache.length; k++)
  23. CACHE[K] =new Integer (j + +); -128 to high values are assigned to the cache array individually
  24. }
  25. Private Integercache () {}//constructor method, no need to construct anything
  26. }

We can clearly see that Integercache has a static member variable cache, which is an array of 256 elements. The cache is also initialized in Integercache, where the I element is an integer object with a value of i-128. While 128 to 127 is the most commonly used integer object, this practice also improves performance to a large extent. Also because of this, "Integeri1=100;integer i2=100;", I1 and I2 get the same object.

Comparing the second experiment in the extension, we learned that when the encapsulation class is run with the underlying type = =, the wrapper class is disassembled, the unboxing result is compared with the underlying type, while the two wrapper classes are run as = = Run with other objects, comparing the addresses of two objects, It also determines whether two references point to the same object.

Extended:

The getandremovecacheproperties method, which gets or removes the cached properties of the JDK set for the integer, and can be adjusted by adjusting the virtual machine-xx:autoboxcachemax=<size> option. The size of the auto-boxing pool

  1. Private static String Integercachehighpropvalue;
  2. static void Getandremovecacheproperties () {
  3. if (!sun.misc.vm.isbooted ()) {
  4. Properties props= system.getproperties ();
  5. Integercachehighpropvalue=
  6. (String) Props.remove ("Java.lang.Integer.IntegerCache.high");
  7. if (integercachehighpropvalue!=null)
  8. System.setproperties (props); //Remove from System props
  9. }
  10. }
Set the-xx:autoboxcachemax=<size> option to test the code again <3>

In Eclipse, select the source file, right-click Run As->runconfiguratio--->arguments, and make the following settings in VM Arguments:

Java Auto Boxing and unpacking those things

Related Article

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.