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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |