← Chapter 7 — Input, Wrappers & Lambdas

28. Wrapper Classes & Autoboxing

mixed

Description

Wrapper classes represent primitive values as objects. For example, Integer wraps int and Double wraps double.

Wrappers are needed by generic collections and provide parsing utilities. Java can automatically convert between a primitive and its wrapper in many common situations.

Subtopics

Autoboxing

Description

Java can wrap a primitive automatically.

Explanation

This happens when an object is required.

Example

Integer score = 92;

Parsing text

Description

Wrapper methods convert String values.

Explanation

Invalid numeric text throws NumberFormatException.

Example

int score = Integer.parseInt("92");

Explanation

Use primitive types for simple calculations unless an object is required. A wrapper variable can be null, so unboxing a null wrapper causes NullPointerException.

Example

public class WrapperDemo {
    public static void main(String[] args) {
        String scoreText = "92";
        Integer score = Integer.parseInt(scoreText);
        System.out.println(score + 8);
    }
}

Key points

  • Integer wraps int.
  • Autoboxing wraps primitives automatically.
  • parseInt converts valid numeric text.

Open reference