Wrapper Classes
Wrapper classes are object versions of Java's primitive types. Every primitive type has a matching wrapper class, letting a primitive value be treated as a full-fledged object when that's what the situation calls for.
Primitive-to-Wrapper Reference
| Primitive | Wrapper Class |
|---|---|
int | Integer |
double | Double |
float | Float |
long | Long |
short | Short |
byte | Byte |
char | Character |
boolean | Boolean |
Why Wrapper Classes Are Needed
Java's collection classes — ArrayList, HashMap, and the rest of the Collections
Framework — can only hold objects, not primitive values. A List<int> is not legal
Java. Wrapper classes bridge this gap: a List<Integer> works because Integer
is an object, even though it represents a plain int underneath.
List<Integer> scores = new ArrayList<>();
scores.add(95); // int 95 is autoboxed into an Integer
Autoboxing and Unboxing
Modern Java converts between primitives and their wrappers automatically. Converting a primitive into its wrapper is called autoboxing; converting a wrapper back into a primitive is called unboxing. Both happen behind the scenes, without any explicit cast.
Example: Autoboxing and Unboxing
public class BoxingDemo {
public static void main(String[] args) {
Integer i = 5; // autoboxing: int 5 becomes an Integer object
int n = i; // unboxing: Integer object becomes a plain int
System.out.println(i + n); // 10
}
}
Common Wrapper Methods
Wrapper classes also come with handy static utility methods, most commonly for converting between
Strings and their numeric or boolean equivalents.
int n = Integer.parseInt("42"); // String -> int
String s = Integer.toString(42); // int -> String
double d = Double.parseDouble("3.14"); // String -> double