Java ยท Chapter 38 of 42

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.

Syntax
Integer i = 5; // autoboxing
int j = i; // unboxing

Autoboxing 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.

Example 1 (java)
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);
  }
}
Output
10 10 42

boxed 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.
๐Ÿ’ก Note: Comparing wrapper objects with == can give surprising results; use equals() to compare their values.

๐Ÿ“ Quick Quiz

1. What is the wrapper class for int?

2. What is autoboxing?

3. Why are wrapper classes needed for collections?