This is a new content introduced after jdk1.5. As I insist that publishing is the best memory, I decided to replace my memory with a blog:
The Java Language Specification says: In many cases packaging and unpacking are done by the compiler itself (in this case packaging is called boxing, and unpacking is called unboxing);
In fact, according to my own understanding, automatic boxing can be simply understood as encapsulating basic data types into object types to comply with Java's object orientation; for example, use int as an example:
Copy the code code as follows:
//Declare an Integer object
Integer num = 10;
//The above statement uses automatic boxing: parsed as
Integer num = new Integer(10); The above is a good example, 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 do this Statement, this is the charm of autoboxing to automatically convert basic data types into corresponding encapsulated types. After becoming an object, you can call all the methods declared by the object to automatically unbox it: hence the name, it means to re-convert the object into a basic data type:
//boxing
Integer num = 10;
//unboxing
int num1 = num; A very typical use of automatic unboxing is when performing operations: because objects are not directly operated, but must be converted into basic data types before addition, subtraction, multiplication and division can be performed.
Integer num = 10;
// Automatic unboxing is implicit when performing calculations
System.out.print(num--); Haha, it should feel very simple. Now I will talk about something a little more difficult.
//Numbers outside -128~127
Integer num1 = 297; Integer num2 = 297;
System.out.println("num1==num2: "+(num1==num2));
// Number within -128~127
Integer num3 = 97; Integer num4 = 97;
System.out.println("num3==num4: "+(num3==num4)); The printed result is: num1==num2: false num3==num4: true
It's strange: this is due to Java's design of automatic boxing and unboxing of Integer and int. It is a mode: called flyweight mode (flyweight)
In order to increase the reuse of simple numbers, Java defines: During automatic boxing, for values between 128 and 127, after they are boxed into Integer objects, they will be stored in memory for reuse, and there will always be only one object. And if it exceeds the value between 128 and 127, the boxed Inte The ger object will not be reused, which is equivalent to creating a new Integer object every time it is boxed; understand, the above phenomenon is caused by the use of automatic boxing. If you do not use automatic boxing, but follow Like general classes, if you use new to instantiate, a new object will be created every time new is used;
This automatic boxing and unboxing is not only used in basic data types, but also in the String class. For example, when we often declare a String object:
Copy the code code as follows:
String str = "sl";
//Replace the following declaration method
String str = new String("sl");
Autoboxing and unboxing of basic data (Primitive) types are functions provided since J2SE 5.0. Although it provides convenience for you to package basic data types, it also hides the details. It is recommended to use it only when you can distinguish the difference between basic data types and objects.
autoboxing and unboxing
In Java, almost everything to be processed is an object (Object). For example, the Scanner used before is an object, and the String (String) is also an object. We will see more objects later. However, basic data types are not objects, that is, variables you define using int, double, boolean, etc., and literal constants you write directly in.
In the previous section, we have roughly seen the convenience of operating objects, and anyone who has used Java for a while knows that sometimes it is necessary to convert basic data types into objects. For example, when using the put() method of a Map object, the parameters that need to be passed in are objects rather than basic data types.
You need to use wrapper types (Wrapper Types) to wrap basic data types into objects. In the previous section, you already know that before J2SE 5.0, you need to use the following statement to wrap int into an Integer object: Integer integer = new Integer(10) ;
The auto-boxing function is provided after J2SE 5.0. You can directly use the following statement to pack basic data types: Integer integer = 10;
When compiling, the compiler will automatically determine whether to perform automatic boxing based on the statements you wrote. In the above example, integer refers to an instance of the Integer class. The same action can be applied to basic data types such as boolean, byte, short, char, long, float, double, etc. The corresponding wrapper types (Wrapper Types) Boolean, Byte, Short, Character, Long, Float or Double will be used respectively. Let's directly use the autoboxing function to rewrite Example 4.4.
Example 4.5 AutoBoxDemo.java
Copy the code code as follows:
public class AutoBoxDemo {
public static void main(String[] args) {
Integer data1 = 10;
Integer data2 = 20;
//Convert to double value and divide by 3
System.out.println(data1.doubleValue() / 3);
//Compare two values
System.out.println(data1.compareTo(data2));
}
}
The program seems much simpler. data1 and data2 are instances of Integer at runtime and can directly perform object operations. The result is as follows:
3.3333333333333335
1
The method of using automatic boxing can also be as follows:
Copy the code code as follows:
int i = 10;
Integer integer = i;
You can also use the more general java.lang.Number class for autoboxing. For example:
Number number = 3.14f;
3.14f will be automatically boxed as Float and then assigned to number.
Starting from J2SE 5.0, automatic boxing and automatic unboxing are available, that is, the basic data form information in the object is automatically taken out of the object. For example, it is possible to write the following:
Copy the code code as follows:
Integer fooInteger = 10;
int fooPrimitive = fooInteger;
After fooInteger is referenced to an instance that is automatically boxed as Integer, if it is assigned to a variable fooPrimitive of type int, it will automatically be changed to type int and then assigned to fooPrimitive. During operation, automatic boxing and unboxing can also be performed. For example:
Copy the code code as follows:
Integer i = 10;
System.out.println(i + 10);
System.out.println(i++);
In the above example, 20 and 10 will be displayed. The compiler will automatically perform automatic boxing and unboxing, that is, 10 will be boxed first, and then unboxed first when i + 10, and the addition operation will be performed; the i++ line will also be boxed first. Unbox and then perform increment operation. Let’s look at another example:
Copy the code code as follows:
Boolean boo = true;
System.out.println(boo && false);
The same boo is originally an instance of Boolean. When performing an AND operation, boo will be unboxed first, and then ANDed with false, and the result will display false.
///////////////////////////////////////////////////// /////////////////
Boxing: Converting from a basic type to an Object type is called boxing; ***Unboxing: The operation of converting from an Object to a basic type is called unboxing. This operation is commonly used in the reflection process.
Packing: Create an Object instance in the heap and copy the value you specify; ***Unboxing: Determine whether the information in the heap pointed to by the reference is of the type to be split, and take the value from the heap and send it to the stack variable, otherwise an exception will be reported
///////////////////////////////////////////////////// //////////////////
Boxing is a hermit conversion of a value type to an object type or to any interface type that the value type implements.
Boxing a value type allocates an object instance and copies the value into a new object.
Copy the code code as follows:
int i=123;
object o=i;
The result of this sentence is to create an object o on the stack, which references a value of type int on the heap. This value is assigned to variable i
A copy of the value type value.
Below is a display that performs the boxing conversion
Copy the code code as follows:
int i=123;
object o=(object)i;
This example converts the integer variable i to the object o through boxing. In this way, the value stored in variable i changes from 123 to 456. This example shows that the object retains an original copy of the content. That is 123.
Unboxing is an explicit conversion from an object type to a value type or from an interface type to a value type that implements the interface. Unboxing operations include:
Checks the object instance to ensure it is a boxed value of the given value type.
Copies the value from the instance into a value type variable.
example:
Copy the code code as follows:
int i=123;
object box=i;
int j=(int)box;