Skip to content

Module 7 · Core Java APIs — topic 1 of 4

Wrapper Classes and Autoboxing

Integer, Double, Boolean and the other wrappers, automatic boxing and unboxing, the Integer cache trap with ==, null unboxing, and useful static helper methods.

Beginner 12 min read·Lesson 23 of 39 in Java Programming

Learning objectives

  • Explain why wrapper classes exist
  • Predict where autoboxing and unboxing happen
  • Avoid the == and null-unboxing traps

Definition

A wrapper class is an object type that holds one primitive value — Integer for int, Double for double, and so on. Autoboxing converts a primitive to its wrapper automatically, and unboxing converts back, whenever the context requires.

Introduction

Java's collections and generics work only with objects, so a List<int> is not allowed. Each primitive therefore has a matching wrapper class: Integer, Long, Double, Float, Short, Byte, Character and Boolean. Thanks to autoboxing you rarely have to convert by hand — but the conversions are still there, and they occasionally bite.

Why it matters

Every List<Integer> or Map<String, Double> you write relies on boxing.

The Integer == Integer bug is one of the best-known Java gotchas and a favourite interview question.

Detailed explanation

Boxing and unboxing. Integer x = 5; boxes the int automatically (it calls Integer.valueOf(5)). int y = x + 1; unboxes x (calls x.intValue()). The compiler inserts these calls wherever an object or a primitive is needed.

Wrappers are immutable objects. x++ on an Integer unboxes, adds and boxes a *new* Integer.

Comparing wrappers. == on two wrapper objects compares references. Integer.valueOf caches values from −128 to 127, so == happens to work for small numbers and fails for larger ones. Always compare wrapper values with equals, or unbox first.

null. A wrapper variable can be null. Unboxing a null — for example int n = map.get("missing"); — throws NullPointerException.

Useful static methods. Integer.parseInt, Integer.valueOf, Integer.toBinaryString, Integer.MAX_VALUE, Integer.compare(a, b), Integer.sum, Character.isDigit, Character.isLetter, Character.toUpperCase, Double.isNaN and Boolean.parseBoolean.

Performance. Boxed numbers take more memory and time than primitives. Use primitives (int[], long loop counters) in performance-sensitive code and wrappers where objects are required (collections, generics, nullable values).

Syntax

Java
Integer boxed = 42; // autoboxing
int plain = boxed; // unboxing
List<Integer> nums = new ArrayList<>();
nums.add(7); // boxes 7
int first = nums.get(0); // unboxes
boolean same = boxed.equals(42); // compare values with equals
int n = Integer.parseInt("123");
  • Never compare wrapper objects with ==.
  • Unboxing null throws NullPointerException.
  • valueOf returns a (possibly cached) object; parseXxx returns a primitive.

Code examples

Boxing, unboxing and helpers

Java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> marks = new ArrayList<>();
marks.add(78); // autoboxing
marks.add(91);
int total = 0;
for (int m : marks) total += m; // unboxing
System.out.println(marks + " total " + total);
System.out.println(Integer.toBinaryString(10) + " " + Integer.toHexString(255) + " " + Integer.parseInt("ff", 16));
System.out.println(Character.isDigit('7') + " " + Character.isLetter('7') + " " + Character.toUpperCase('q'));
System.out.println(Integer.compare(3, 9) + " " + Integer.max(3, 9) + " " + Double.isNaN(0.0 / 0.0));
}
}
Output
[78, 91] total 169
1010 ff 255
true false Q
-1 9 true

The == trap

Java
public class Main {
public static void main(String[] args) {
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b); // cached objects
System.out.println(c == d); // different objects
System.out.println(c.equals(d)); // compare values
System.out.println(c.intValue() == d); // unboxed comparison
}
}
Output
true
false
true
true

More examples

Counting with a map and the null-unboxing pitfall

Java
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
String text = "to be or not to be that is the question";
Map<String, Integer> counts = new TreeMap<>();
for (String w : text.split(" ")) {
counts.merge(w, 1, Integer::sum); // boxing and unboxing behind the scenes
}
System.out.println(counts);
Map<String, Integer> stock = new HashMap<>();
stock.put("pen", 12);
Integer maybe = stock.get("pencil"); // null: no such key
System.out.println("pencil: " + maybe);
try {
int pencils = stock.get("pencil"); // unboxing null
System.out.println(pencils);
} catch (NullPointerException e) {
System.out.println("NullPointerException while unboxing");
}
int safe = stock.getOrDefault("pencil", 0);
System.out.println("pencil (safe): " + safe);
}
}
Output
{be=2, is=1, not=1, or=1, question=1, that=1, the=1, to=2}
pencil: null
NullPointerException while unboxing
pencil (safe): 0

Step-by-step explanation

  • A TreeMap keeps its keys sorted, so the counts print alphabetically.
  • counts.merge(w, 1, Integer::sum) inserts 1 for a new word or adds 1 to the existing Integer; values are boxed and unboxed automatically.
  • stock.get("pencil") returns null because the key is missing; storing it in an Integer is fine.
  • Assigning the same call to an int forces unboxing of null, which throws NullPointerException.
  • getOrDefault(key, 0) returns a safe default instead of null.

Expected output

Running “Counting with a map and the null-unboxing pitfall” prints exactly:

TextOutput
{be=2, is=1, not=1, or=1, question=1, that=1, the=1, to=2}
pencil: null
NullPointerException while unboxing
pencil (safe): 0

Practical applications

  • Storing numbers in collections and maps
  • Representing optional numeric values (null meaning 'not set') in database records
  • Parsing and formatting numbers in different bases

Best practices

  • Use primitives unless an object is required.
  • Compare wrappers with equals or Integer.compare.
  • Use getOrDefault or null checks before unboxing map values.

Common mistakes

Comparing Integers with ==

Avoid

if (scoreA == scoreB) ... // Integer objects

Prefer

if (scoreA.equals(scoreB)) ...

== compares references; it only appears to work for cached values between -128 and 127.

Unboxing a missing map value

Avoid

int qty = stock.get(item);

Prefer

int qty = stock.getOrDefault(item, 0);

get returns null for missing keys, and unboxing null throws NullPointerException.

Important notes

  • The wrapper constructors such as new Integer(5) are deprecated; use valueOf or autoboxing.
  • The Integer cache upper limit can be raised with a JVM option, another reason never to rely on ==.

Key takeaways

  • Each primitive has an immutable wrapper class used where objects are required.
  • Autoboxing and unboxing are inserted by the compiler.
  • Compare wrappers with equals; beware of unboxing null.

Try it yourself

  1. 1
    Count the frequency of each digit in a long number using a Map<Character, Integer>.
  2. 2
    Write a method that returns the maximum of a List<Integer> or null for an empty list, and handle the null safely in the caller.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

6 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat happens when you unbox a null Integer, e.g. `int n = map.get("missing");`?
  • BeginnerWhat is printed?
Practise this topic