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.
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
- 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
[78, 91] total 169 1010 ff 255 true false Q -1 9 true
The == trap
true false true true
More examples
Counting with a map and the null-unboxing pitfall
{be=2, is=1, not=1, or=1, question=1, that=1, the=1, to=2}
pencil: null
NullPointerException while unboxing
pencil (safe): 0Step-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 anIntegeris fine.- Assigning the same call to an
intforces 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:
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
Prefer
== compares references; it only appears to work for cached values between -128 and 127.
Unboxing a missing map value
Avoid
Prefer
get returns null for missing keys, and unboxing null throws NullPointerException.
Important notes
- The wrapper constructors such as
new Integer(5)are deprecated; usevalueOfor 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
- 1Count the frequency of each digit in a long number using a Map<Character, Integer>.
- 2Write 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?