Codectionary / Developer documentation / Java

Wrapper Classes & Autoboxing

Every Java primitive type has a corresponding wrapper class - int has Integer, double has Double, boolean has Boolean, and so on. Wrapper classes turn primitive values into full objects, which is necessary when working with generics or collections like ArrayList, since those can only hold objects, not primitives. Autoboxing and unboxing let Java automatically convert between a primitive and its wrapper class as needed.

Syntax

WrapperClass variable = primitiveValue; // autoboxing

Examples

Basic Wrapper Classes

Each primitive type's corresponding wrapper class.

Integer boxedInt = 42;
Double boxedDouble = 3.14;
Boolean boxedBoolean = true;
Character boxedChar = 'A';

System.out.println(boxedInt);
System.out.println(boxedDouble);

Autoboxing and Unboxing

Java automatically converts between primitives and their wrapper types where needed.

int primitive = 10;
Integer boxed = primitive;    // autoboxing: int -> Integer

Integer wrapped = 25;
int unboxed = wrapped;         // unboxing: Integer -> int

System.out.println(boxed + unboxed);  // 35, works seamlessly

Why Wrapper Classes Matter for Collections

Generic collections like ArrayList cannot hold primitives directly - they require wrapper classes.

import java.util.ArrayList;

// ArrayList<int> numbers = new ArrayList<>();  // Error! primitives not allowed

ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);   // autoboxed to Integer automatically
numbers.add(20);

int first = numbers.get(0);  // auto-unboxed back to int
System.out.println(first);

Useful Wrapper Class Methods

Wrapper classes provide static utility methods for parsing and converting values.

String numText = "123";
int parsed = Integer.parseInt(numText);
System.out.println(parsed + 1);  // 124

System.out.println(Integer.MAX_VALUE);  // 2147483647
System.out.println(Integer.MIN_VALUE);  // -2147483648

System.out.println(Integer.toBinaryString(10));  // 1010

Best practices

  • Use wrapper classes when working with generics and collections (ArrayList<Integer>, not ArrayList<int>), since generics require object types
  • Prefer primitives over wrapper classes for simple local computation - they avoid the small overhead of object creation and unboxing
  • Be careful comparing wrapper objects with == - like String, it compares references, not values, outside a small cached range (-128 to 127 for Integer)
  • Watch for a NullPointerException when unboxing a wrapper object that is null - a null Integer cannot be auto-unboxed to int

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading