beginnerFree

Wrapper Classes

Autoboxing - primitives meet objects

Wrapper Classes

Wrapper classes let primitives act as objects. Autoboxing handles conversion automatically.

The narrated version of this skribble — tap play for the full-size video.

0:00 / 2:18

The Big Picture

Wrappers convert primitives into objects: int to Integer. Required for collections, generics, and object-expecting APIs.

  • Each primitive has one: int / Integer, char / Character
  • Autoboxing/unboxing converts automatically
  • Immutable - values can't change once created

Utility methods: Integer.parseInt(), Double.isNaN()

How It Works

Autoboxing: Integer x = 42 calls Integer.valueOf(42). Unboxing: int y = x calls x.intValue().

  • Cached values: Integer.valueOf(-128 to 127) reused
  • Outside it, == is not portable - use equals()
  • Parse strings: Integer.parseInt("123")
  • Convert back: String.valueOf(42)

In the Java Landscape

Collections require objects: List<Integer> not List<int>.

  • Autoboxing (Java 5+) made wrappers mostly transparent
  • Primitive streams avoid boxing: IntStream, DoubleStream
  • OptionalInt, OptionalDouble for primitive optionals
  • Valhalla project (future) may allow List<int>
  • Records keep declared types; normal boxing applies

Pitfalls and Best Practices

  • Don't use == for wrappers (cache boundary surprises)
  • Always use equals() for wrapper comparison
  • Null unboxing throws NullPointerException
  • Avoid autoboxing in tight loops (GC pressure)
  • Prefer primitives for performance-critical code
  • Use primitive streams (IntStream) in pipelines
#java#fundamentals#wrapper-classes