Java Wrapper Classes
Wrapper classes provide object representations of Java's primitive types: Integer for int, Double for double, Boolean for boolean, Character for char, and so on.
Wrapper classes are needed when you require an object, such as storing primitive-like values in collections (which only hold objects), and Java automatically converts between primitives and wrappers via autoboxing/unboxing.
Integer i = 5; // autoboxing
int j = i; // unboxingAutoboxing and unboxing
Autoboxing automatically converts a primitive to its wrapper (int -> Integer); unboxing converts back (Integer -> int). This happens transparently in most code.
Useful wrapper methods
Wrapper classes provide utility methods like Integer.parseInt(String) to convert a String to an int, and Integer.MAX_VALUE for type limits.
public class Main {
public static void main(String[] args) {
Integer boxed = 10;
int unboxed = boxed;
int parsed = Integer.parseInt("42");
System.out.println(boxed + " " + unboxed + " " + parsed);
}
}10 10 42boxed is autoboxed into an Integer, unboxed is converted back to int, and parseInt converts a String to an int.
Key points
- Every primitive type has a corresponding wrapper class.
- Autoboxing converts primitive to wrapper automatically.
- Unboxing converts wrapper back to primitive automatically.
- Collections can only store objects, so wrappers are required there.
