Home > Java > javaTutorial > body text

How Does Auto Boxing/Unboxing Work in Java?

Barbara Streisand
Release: 2024-11-14 12:37:02
Original
350 people have browsed it

How Does Auto Boxing/Unboxing Work in Java?

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;
Copy after login
0: bipush        42
2: invokestatic  #16                 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
5: astore_1      
Copy after login

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);
Copy after login
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      
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template