EMZETT.
Login

Wrapper Classes

In short: A class that wraps a primitive data type (e.g. a simple integer) into a full-fledged object — needed when an API or collection expects an object instead of a primitive value.

In more detail: Primitive values alone have no methods and can’t be stored in object-based data structures like a list — a wrapper class gives the primitive value an object shell with useful additional functions (e.g. string conversion, comparison methods). Many languages automatically convert between the primitive value and the wrapper object (auto(un)boxing), which can cause performance traps in practice if it happens very frequently unnoticed.

In Depth

int primitive = 5;              // primitive value - not an object
Integer wrapper = 5;            // wrapper object - has methods like .toString()
 
List<Integer> list = new ArrayList<>();
list.add(5);   // works - "5" is automatically "boxed" into Integer
// list.add(int) would NOT work - collections only store objects

In languages like Java, every primitive type has a corresponding wrapper class (int ↔ Integer, double ↔ Double, boolean ↔ Boolean, etc.). The reason this distinction is needed at all: many object-based structures (collections, generics) are designed to work exclusively with objects (i.e. reference types), not with raw primitive values — wrapper classes bridge the gap between the two worlds.

The automatic conversion between primitive value and wrapper object (autoboxing/auto-unboxing) usually makes this invisible in everyday code — you simply write list.add(5), without calling new Integer(5) yourself. But this hides two pitfalls:

  • Performance: every boxing operation creates (in many cases) a new object in memory — if this happens very frequently unnoticed in a loop with many iterations, it can be noticeably slower than pure primitive arithmetic.
  • Comparison with ==: wrapper objects are reference types — two Integer objects with the same value aren’t necessarily ==-equal (see Comparison Operators), even though small numbers in some languages appear equal anyway due to internal cache optimisations — a deceptive, inconsistent behaviour that’s better not relied on at all, and instead the content comparison method should be used consistently.

See also: Non-primitive Types, byte