• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

The Problem

Java’s type system has two worlds: primitives (int, boolean) and objects. Collections like ArrayList and HashMap can only store objects, not primitives. Similarly, generic types (List<Integer>) require object types. Without wrapper classes, developers would need to manually convert between primitive values and objects whenever using these APIs.

Core Idea

Wrapper classes provide an object wrapper for each primitive type: Integer for int, Boolean for boolean, Character for char, and so on. Since Java 5, autoboxing and unboxing automatically convert between primitives and their wrappers, making the transition seamless.

How It Works

When a primitive is assigned to a wrapper type (e.g., Integer x = 42), the compiler inserts code to call Integer.valueOf(42). When a wrapper is used in a primitive context (e.g., int y = x + 1), the compiler inserts x.intValue(). The valueOf() methods for Integer and Boolean use caching for commonly used values.

Visual Explanation

java_wrappers Prim Primitive int x = 42 AutoBox Autoboxing x -> Integer.valueOf(42) Prim->AutoBox assignment to wrapper Wrap Wrapper Integer y = 42 AutoBox->Wrap AutoUnbox Unboxing y.intValue() Wrap->AutoUnbox usage in expression Result Primitive int z = x + y AutoUnbox->Result

Semantic Network

semantic_wrappers THIS Wrapper Classes DT Data Types THIS--DT built from COLL Collections Framework THIS--COLL builds into GEN Generics THIS--GEN builds into PERF Performance THIS--PERF related

Key Properties

  • Eight wrapper classes: Byte, Short, Integer, Long, Float, Double, Boolean, Character
  • Value caching: Integer caches -128 to 127; Boolean caches TRUE and FALSE
  • Immutable: Wrapper objects cannot be changed after creation
  • Utility methods: parseInt(), toString(), compareTo(), equals()

Connections

Edge Cases & Gotchas

  • == vs equals() for wrappers: new Integer(100) == new Integer(100) is false (different objects)
  • NullPointerException: Unboxing a null wrapper throws NPE: Integer x = null; int y = x; crashes
  • Performance penalty: Autoboxing creates unnecessary objects in loops — use primitives for math-heavy code
  • Cache boundary: Integer.valueOf(200) != Integer.valueOf(200) is true (outside cache range)