Autoboxing and unboxing are features in Java that automatically convert primitive data types into their corresponding wrapper classes and vice versa. These features were introduced in Java 5 to simplify code and improve readability.
State: Primitive int val = 10;
What happens if you try to unbox a null Wrapper object? Try it below:
Java automatically performs boxing when a primitive is assigned to a wrapper type, and unboxing when a wrapper object is assigned to a primitive variable.
// Autoboxing: int to Integer
int a = 10;
Integer obj = a;
// Unboxing: Integer to int
int b = obj;
// Demonstrating autoboxing and unboxing in Java
public class AutoboxDemo {
public static void main(String[] args) {
Integer x = 50;
int y = x;
System.out.println("Wrapper value: " + x);
System.out.println("Primitive value: " + y);
}
}
Wrapper value: 50
Primitive value: 50
In this example, the primitive value 50 is automatically converted into an Integer object (autoboxing). Later, the same object is converted back into a primitive int (unboxing) without explicit method calls.
null values while unboxingDouble and Booleannull wrapper