Auto Boxing/Unboxing in Java
Automatic boxing and unboxing in Java simplifies type conversions between primitive data types and their corresponding wrapper classes. Introduced in JDK 5.0, this feature provides a seamless integration of these two representations.
Auto Boxing
When assigning a primitive value to a wrapper class variable, auto boxing occurs. Contrary to the assumption that the wrapper class constructor is used, the static method valueOf() is invoked instead. This is evident in the bytecode generated for the following code:
Integer n = 42;
0: bipush 42 2: invokestatic #16 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 5: astore_1
The valueOf() method caches the created objects, ensuring resource efficiency.
Auto Unboxing
Conversely, when extracting a primitive value from a wrapper class variable, auto unboxing occurs. This process utilizes the intValue() method for integers (and analogous methods for other types), as illustrated in the bytecode for:
int n = Integer.valueOf(42);
0: bipush 42 2: invokestatic #16 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 5: invokevirtual #22 // Method java/lang/Integer.intValue:()I 8: istore_1
This method simply returns the primitive value stored within the wrapper object.
In summary, auto boxing/unboxing involves the use of static methods valueOf() and intValue() (or similar) to transparently convert between primitive and wrapper class representations. This simplifies code and improves performance by utilizing caching mechanisms.
The above is the detailed content of How Does Auto Boxing/Unboxing Work in Java?. For more information, please follow other related articles on the PHP Chinese website!