Wrapper Classes
Every one of Java's eight primitive types has a matching class that "wraps" that primitive value inside a full object. These are the wrapper classes, and they exist to bridge the gap between primitives — which are not objects — and the parts of Java that require objects.
The 8 Primitive-to-Wrapper Pairs
Primitive | Wrapper Class |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
Why Wrapper Classes Exist
Primitives are extremely efficient, but they are not objects — and a significant part of Java, especially the generics system and the collections framework, is designed to work only with objects. Wrapper classes give primitive values an object identity so they can participate in that part of the language.
Reason 1: Generic Collections Require Objects
This does NOT compile
import java.util.List;
import java.util.ArrayList;
public class BadGenericsDemo {
public static void main(String[] args) {
List<int> numbers = new ArrayList<int>(); // compile error!
}
}The correct version
import java.util.List;
import java.util.ArrayList;
public class GoodGenericsDemo {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
System.out.println(numbers);
}
}[10, 20, 30]
Reason 2: Representing "No Value"
null represents an unknown score
public class NullableScoreDemo {
public static void main(String[] args) {
Integer score = null; // "no score recorded yet"
if (score == null) {
System.out.println("No score recorded");
} else {
System.out.println("Score: " + score);
}
}
}No score recorded
Useful Utility Methods
Common wrapper utility methods
public class WrapperUtilityDemo {
public static void main(String[] args) {
int fromString = Integer.parseInt("42");
double priceFromString = Double.parseDouble("19.99");
System.out.println(fromString + 8);
System.out.println(priceFromString + 0.01);
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.toBinaryString(42));
System.out.println(Boolean.parseBoolean("true"));
}
}50 20.0 2147483647 -2147483648 101010 true
Method | Purpose |
Integer.parseInt(str) | Convert a String to an int |
Double.parseDouble(str) | Convert a String to a double |
Integer.MAX_VALUE / MIN_VALUE | The largest/smallest possible int |
Integer.toBinaryString(n) | Represent an int in binary |
Boolean.parseBoolean(str) | Convert a String to a boolean |
Integer.valueOf(n) | Get the Integer wrapper for an int |