What are autoboxing and unboxing in Java?
Each primitive has a wrapper class: int – Integer, double – Double, boolean – Boolean. Java converts between them by itself:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Integer boxed = 5; // autoboxing
int plain = boxed; // unboxing
List<Integer> list = new ArrayList<>();
list.add(10); // autoboxing
int first = list.get(0); // unboxing
System.out.println(boxed + plain + first);
Integer a = 127, b = 127, c = 1000, d = 1000;
System.out.println(a == b); // true: small values are cached
System.out.println(c == d); // false: different objects
System.out.println(c.equals(d));
}
}
Output
20
true
false
true
Compare wrapper objects with equals(), not with ==. Unboxing a null gives a NullPointerException.
Learn more about the similar topics:
| Tutorials |
|---|
| Java Variables |
| Java Data Types |
| Java Type Casting |
| Java Operators |
| Java User Input with Scanner |
| Java Math Class |
| Exercises & Assignments |
|---|
| Print your name and age with variables |
| Swap two numbers with and without a third variable |
| Convert Celsius to Fahrenheit |
| Interview Questions & Answers |
|---|
| What are the primitive data types in Java? |
| What are autoboxing and unboxing in Java? |