Autoboxing and Unboxing in Java
Overview
In this tutorial, we will learn about Autoboxing and Unboxing in Java. These features were introduced in J2SE 5.
Autoboxing
Autoboxing is the automatic conversion by the Java compiler of the primitive type to the corresponding Wrapper class object.
Example:
Converting an int type to an Integer wrapper class object.
Integer i = 9; // autoboxing int to Integer
Character c = ‘a’; // autoboxing char to Character
Table that shows the Java primitive types and the corresponding Wrapper classes.
Java Primitive Type | Java Wrapper class |
---|---|
boolean | Boolean |
byte | Byte |
char | Character |
int | Integer |
float | Float |
double | Double |
short | Short |
long | Long |
Sample Code
public class AutoBoxingDemo { public static void main(String[] args) { ArrayList list = new ArrayList<>(); for (int i = 1; i < 10; i++) { // int to -> Integer list.add(Integer.valueOf(i)); } } }
In the above code snippet list is a list of Integer objects. In the loop we have added int primitives type to the list. Notice that, Java complier does not complain about the type mismatch. The complier creates an Integer object from i and adds to the list. This conversion is called autoboxing. Autoboxing can be done during assignment, method invocation, etc.
Unboxing
Unboxing is the reverse conversion. It is the automatic conversion of Wrapper class object to their corresponding primitive type by the Java compiler.
Sample Code Example
import java.util.ArrayList; //UnBoxing Demo Program //Java Tutorials - www.TestingDocs.com public class UnBoxingDemo { public static void main(String[] args) { int primInt = 0; Integer i = Integer.valueOf(9); // Unboxing through assignment ArrayList list = new ArrayList<>(); list.add(3.14f); float f = list.get(0); // Unboxing through method call primInt = foo(i); System.out.println(primInt); } public static int foo(int i) { return i; } }
—
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :