Sub topic 1
Java Wrapper Classes and Autoboxing: Primitives and Objects
Prerequisites
You should know Java primitive types such as int, long, double, boolean, and char. You should also know basic classes, objects, ==, equals, and generic collections such as List<Integer>.
Primitives and objects: why Java has both
A primitive stores a value directly. For example, an int stores a whole number. Primitives are efficient, but they are not objects. They do not have methods and cannot be used as type arguments in generics.
A reference type stores a reference to an object. An object can have methods, can be null, and can be used with APIs that require objects. Java therefore provides a wrapper class for each primitive.
Meet the wrapper classes
| Primitive | Wrapper |
|---|---|
| `int` | `Integer` |
| `long` | `Long` |
| `double` | `Double` |
| `boolean` | `Boolean` |
| `char` | `Character` |
The other pairs are byte and Byte, short and Short, and float and Float. Collections use wrappers because generic type arguments must be reference types:
import java.util.ArrayList;
import java.util.List;
public class WrapperDemo {
public static void main(String[] args) {
List<Integer> values = new ArrayList<>();
values.add(42);
Integer object = values.get(0);
System.out.println(object);
}
}Autoboxing and unboxing: what the compiler does for you
Autoboxing converts a primitive to its wrapper. Unboxing converts a wrapper to its primitive. The compiler inserts these conversions when the types are used together.
In the example, values.add(42) is approximately compiled as values.add(Integer.valueOf(42)). Assigning the result to a primitive is approximately object.intValue().
Parsing and converting with wrapper methods
Use parseX when you need a primitive and valueOf when you need a wrapper:
int count = Integer.parseInt("42");
Integer boxedCount = Integer.valueOf("42");
String text = Integer.toString(count);
System.out.println(count + 1);
System.out.println(boxedCount);
System.out.println(text);These methods throw NumberFormatException when the input text is not a valid number.
Exercise
Why can List<Integer> store 42 even though 42 is an int?
Show answer
Autoboxing converts the int to an Integer before the list stores it.