In-depth analysis of java automatic packing and unpacking

Source: Internet
Author: User

This is a new content introduced after jdk1.5. As the best memory for posting, I decided to replace my memory with a blog:
The java language specification says: in many cases, packaging and unpackaging are done by the compiler itself (in this case, packaging is packed, and unpackaging is called unpacking );
In fact, according to my own understanding, automatic packing can be simply understood as encapsulating basic data types as object types to conform to java's object-oriented model. For example, int is used as an example:

Copy codeThe Code is as follows: // declare an Integer object
Integer num = 10;
// The above statement uses automatic packing: resolved
Integer num = new Integer (10); The above is a good embodiment, because 10 belongs to the basic data type, in principle it cannot be directly assigned to an object Integer, but after jdk1.5, you can make such a statement, which is the charm of automatic packing.
The basic data type is automatically converted to the corresponding encapsulation type. After becoming an object, you can call all the methods declared by the object.
Automatic box unboxing: the object is renamed as the basic data type:
// Packing
Integer num = 10;
// Unpack
Int num1 = num; a typical use of automatic box unboxing is to perform an operation: because the object is not processed directly, it must be converted to the basic data type before addition, subtraction, multiplication, and division can be performed.
Integer num = 10;
// Automatically Unbox hidden during Calculation
System. out. print (num --); Haha, it should be very simple. Next let's talk about some difficult points,
// In-128 ~ Number not greater than 127
Integer num1 = 297; Integer num2 = 297;
System. out. println ("num1 = num2:" + (num1 = num2 ));
// In-128 ~ Number within 127
Integer num3 = 97; Integer num4 = 97;
System. out. println ("num3 = num4:" + (num3 = num4); the printed result is: num1 = num2: false num3 = num4: true

Strange: this is due to java's automatic packing and unpacking Design for Integer and int. It is a mode called flyweight)
To increase reuse of simple numbers, java defines that after values from-128 to 127 are packed into Integer objects during automatic packing, memory is reused, and only one object exists.
If the value range from-128 to 127 is exceeded, the boxed Integer object will not be reused, which is equivalent to creating an Integer object each time it is packed.
The above phenomenon is caused by the use of automatic packing. If you do not use automatic packing, but like a general class, use new for instantiation, A new object is created every time new is created;
This automatic packing and unpacking method is not only applicable to the basic data type, but also in the String class. For example, when we declare a String object frequently:Copy codeThe Code is as follows: String str = "sl ";
// Replace the following declaration method
String str = new String ("sl ");

Autoboxing and unboxing of the Primitive type are functions provided from J2SE 5.0. Although it provides convenience for you to package basic data types, it also provides convenience to indicate that the details are hidden. We recommend that you use it when distinguishing the differences between basic data types and objects.
Autoboxing and unboxing
In Java, almost all things to be processed are objects. For example, the objects used previously are objects, and strings are also objects, more objects are displayed. However, the basic (Primitive) data type is not an object, that is, the variables defined by you using int, double, boolean, And the literal constants you write directly in.
In the previous section, we have roughly seen the convenience of object operations. Anyone who has been using Java For A While knows that the basic data type sometimes needs to be converted to an object. For example, when a Map object is used to put () A method, the input parameter is an object rather than a basic data type.
You must use Wrapper Types to wrap the basic data type as an object. In the previous section, you know that before J2SE 5.0, the following statement can be used to encapsulate an int as an Integer object: Integer integer = new Integer (10 );
The automatic packing function is provided after J2SE 5.0. You can directly use the following statement to package the basic data type: Integer integer = 10;
During compilation, the compiler automatically determines whether to perform automatic packing based on the statements you write. In the preceding example, integer refers to an Integer class instance. The same action can be applied to basic data Types such as boolean, byte, short, char, long, float, and double. The corresponding Wrapper Types are used respectively) boolean, Byte, Short, Character, Long, Float, or Double. The following code uses the automatic packing function to rewrite example 4.4.

Example 4.5 AutoBoxDemo. javaCopy codeThe Code is as follows: public class AutoBoxDemo {
Public static void main (String [] args ){
Integer data1 = 10;
Integer data2 = 20;
// Convert to double and divide it by 3
System. out. println (data1.doubleValue ()/3 );
// Compare two values
System. out. println (data1.compareTo (data2 ));
}
}

The program seems to be much more concise. data1 and data2 are Integer instances at runtime and can directly perform object operations. The result is as follows:
3.3333333333333335
-1
The automatic packing method can also be as follows:Copy codeThe Code is as follows: int I = 10;
Integer integer = I;

You can also use a more general java. lang. Number class for automatic packing. For example:
Number number = 3.14f;
3.14f is automatically packed as Float and then specified to number.
From J2SE 5.0, it can be automatically packed or unboxing, that is, the basic data form information in the object is automatically extracted from the object. For example, you can write as follows:Copy codeThe Code is as follows: Integer fooInteger = 10;
Int fooPrimitive = fooInteger;

If fooPrimitive is specified to an int type variable after fooInteger is referenced to an instance with automatic packing as Integer, it is automatically converted to int type and then specified to fooPrimitive. During computation, you can also perform automatic packing and unpacking. For example:Copy codeThe Code is as follows: Integer I = 10;
System. out. println (I + 10 );
System. out. println (I ++ );

In the above example, 20 and 10 are displayed, and the compiler automatically packs and unpacks, that is, 10 is first packed, and then I + 10 is first split to perform addition operations; the I ++ row is also split before incremental calculation. Let's look at an example:Copy codeThe Code is as follows: Boolean boo = true;
System. out. println (boo & false );

The same boo is originally a Boolean instance. When performing the AND operation, the boo is first split into bins AND then operated on AND with false. The result is false.
//////////////////////////////////////// //////////////////////////
Packing: Converting from basic type to Object type is called packing; *** unpacking: Converting from Object to multiplication basic type is called unpacking. This operation is often used in the reflection process.
Packing: Create an Object instance in the heap and copy the value you specified to it. *** unpacking: identify whether the information in the heap to which the reference points is of the type to be split, is to extract the heap value to the variable in the stack, otherwise an exception is reported.
//////////////////////////////////////// ///////////////////////////
Packing is a hermit conversion from the value type to the object type or to any interface type implemented by this value type.
Binning a value type will allocate an object instance and copy the value to the new object.Copy codeThe Code is as follows: int I = 123;
Object o = I;

The result of this statement is to create an object o on the stack, and the object references the int type value on the stack. This value is assigned to variable I.
A copy of the Value Type value.
The following shows how to perform the packing conversion.Copy codeThe Code is as follows: int I = 123;
Ojbect o = (object) I;

In this example, the integer variable I is converted to the object o through packing. In this way, the value stored in variable I will be changed from 123 to 456. In this example, the object retains the original copy of the content. 123.
Unboxing is a display conversion from the object type to the value type or from the interface type to the value type that implements this interface. Unboxing includes:
Check the object instance to make sure it is a boxed value of the given value type.
Copy the value from the instance to the value type variable.
Example:Copy codeThe Code is as follows: int I = 123;
Object box = I;
Int j = (int) box;

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.