Boxing and Unboxing
What is Boxing?
Boxing is the automatic conversion of a primitive type to its corresponding wrapper class object. Java automatically converts primitive types to objects when needed.
graph LR
A[Primitive Type] -->|Boxing| B[Wrapper Class Object]
B -->|Unboxing| A
Types of Boxing
Implicit Boxing
Integer objectInt = 42; // Automatic boxing of int to Integer
Double objectDouble = 3.14; // Automatic boxing of double to Double
Explicit Boxing
Integer objectInt = Integer.valueOf(42);
Boolean objectBoolean = Boolean.valueOf(true);
Unboxing Mechanism
Unboxing is the reverse process of converting a wrapper class object back to its primitive type.
Implicit Unboxing
Integer objectInt = 100;
int primitiveInt = objectInt; // Automatic unboxing
Explicit Unboxing
Integer objectInt = Integer.valueOf(200);
int primitiveInt = objectInt.intValue();
Operation |
Performance Impact |
Boxing |
Slight overhead |
Unboxing |
Minimal performance cost |
Frequent boxing/unboxing |
Potential performance bottleneck |
Common Pitfalls
Null Pointer Risks
Integer objectInt = null;
int primitiveInt = objectInt; // Throws NullPointerException
Advanced Example
public class BoxingDemo {
public static void processNumber(Integer number) {
if (number != null) {
System.out.println("Processed number: " + number);
}
}
public static void main(String[] args) {
int primitiveValue = 100;
// Automatic boxing when passing to method
processNumber(primitiveValue);
// Unboxing in calculations
Integer boxedValue = 50;
int result = boxedValue * 2;
System.out.println("Result: " + result);
}
}
LabEx Learning Insight
At LabEx, we emphasize understanding boxing and unboxing to write more robust and efficient Java code, avoiding unnecessary object creation and potential performance bottlenecks.