← Back to Chapters

Autoboxing & Unboxing in Java

? Autoboxing & Unboxing in Java

? Quick Overview

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.

? Key Concepts

  • Autoboxing Primitive → Wrapper Object
  • Unboxing Wrapper Object → Primitive
  • Wrapper classes are immutable
  • Common wrapper classes: Integer, Double, Boolean, Character

? Interactive Demo

 

int (Primitive)
10
 
Integer (Object)

State: Primitive int val = 10;

? The "Null" Trap

What happens if you try to unbox a null Wrapper object? Try it below:

⬇️ Unboxing... ⬇️
?
 

? Syntax & Theory

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.

? View Code Example
// Autoboxing: int to Integer
int a = 10;
Integer obj = a;

// Unboxing: Integer to int
int b = obj;

? Code Example

? View Code Example
// 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);
}
}

? Output

Wrapper value: 50
Primitive value: 50

 

? Explanation

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.

✅ Tips & Best Practices

  • Avoid unnecessary boxing/unboxing in performance-critical code
  • Be careful with null values while unboxing
  • Prefer primitives for simple calculations

? Try It Yourself

  • Create examples using Double and Boolean
  • Test what happens when unboxing a null wrapper
  • Compare performance of boxed vs primitive loops