Primitive Type Wrappers:
Java is primarily an object-oriented language, but for performance and convenience, it includes primitive data types (e.g., int, char, boolean).
- Java provides wrapper classes in the
java.langpackage for each of the 8 primitive data types, which allows primitives to be treated like objects.
Why Use Wrapper Classes?
- To allow primitive values to be treated as objects (e.g., storing them in collections like ArrayList which can only hold objects).
- To provide useful methods for parsing and converting data.
- Unlike primitives, wrapper classes can hold null, representing no value.
- Java automatically converts primitives to objects and vice versa for convenience.
- They’re commonly used in collections, serialization, reflection, and generics.
- Wrapper classes are immutable — once created, their value can’t be changed.
Primitive Types and Their Wrapper Classes:

Autoboxing and Unboxing: Java automatically converts between primitive types and their corresponding wrapper objects.
- Autoboxing: Converting a primitive to a wrapper object automatically. (e.g., int i = 10; Integer obj = i;)
- Unboxing: Converting a wrapper object to a primitive automatically. (e.g., Integer obj = 20; int j = obj;)
Example:
public class BoxingUnboxingDemo {
public static void main(String[] args) {
// Primitive int
int a = 10;
// Boxing: converting int to Integer
Integer obj = Integer.valueOf(a); // Explicit boxing
System.out.println("Boxed Integer object: " + obj);
// Unboxing: converting Integer back to int
int b = obj.intValue(); // Explicit unboxing
System.out.println("Unboxed int value: " + b);
// Autoboxing: automatic conversion from int to Integer
Integer autoBoxed = a;
System.out.println("Auto-boxed Integer: " + autoBoxed);
// Auto-unboxing: automatic conversion from Integer to int
int autoUnboxed = obj;
System.out.println("Auto-unboxed int: " + autoUnboxed);
}
}
Discussion 0