[!NOTE] We briefly touched on Wrapper classes when discussing
ArrayLists. Because Java Generics (<Integer>) can physically only handle Objects living on the Heap memory, they cannot process pure primitives likeintordouble.
Wrapper classes wrap the raw primitive data inside a full Object shell, granting them access to hundreds of methods.
The Wrapper Conversions
| Primitive Data Type | Wrapper Class |
|---|---|
byte |
Byte |
short |
Short |
int |
Integer |
long |
Long |
float |
Float |
double |
Double |
boolean |
Boolean |
char |
Character |
Creating Wrapper Objects
You can instantiate Wrapper classes just like any other object.
Integer myInt = 5; // Automatically wraps it!
Double myDouble = 5.99;
Character myChar = 'A';
// Because they are fully-fledged Objects, you can call Methods on them!
System.out.println(myInt.intValue()); // Extracts the raw primitive back out.
System.out.println(myDouble.doubleValue());
// Converting an Integer object directly into a String representation!
String myString = myInt.toString();
System.out.println(myString.length()); // Outputs 1
Autoboxing and Unboxing
Historically, developers had to manually write Integer myInt = new Integer(5); and then invoke myInt.intValue() to extract the 5 out every time they did math.
To reduce boilerplate, modern Java compilers employ Autoboxing and Unboxing.
- Autoboxing: The automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an
intdirectly to anInteger. - Unboxing: The aggressive automatic conversion of wrapper class to primitive.
// Autoboxing:
// Java sees primitive '10', creates an 'Integer' object in Heap memory silently, and adds it!
ArrayList<Integer> li = new ArrayList<>();
li.add(10);
// Unboxing:
// Java retrieves the 'Integer' object, quietly extracts the intValue(), and does the raw math!
int result = li.get(0) + 15;
[!CAUTION] Avoid Autoboxing in massive
forloop mathematical calculations. Constructing and destroying 10,000,000Integerobjects in a tight loop is extremely CPU intensive compared to using rawintprimitives.