- Prerequisites
- 3.3 Primitive vs Reference · 3.4 Type Conversion
- Covers
- Integer · Long · Double · Boolean · Character · Boxing · Unboxing · Wrapper caching
- Related
- B1V2 Generics and Collections · B1V3 Streams (IntStream) · Book 2 Vol II (memory and GC)
On this page
1Concept / Definition
A wrapper class is an immutable object that holds a single primitive value. There is one per primitive type: Byte, Short, Integer, Long, Float, Double, Character and Boolean. Boxing converts a primitive into its wrapper; unboxing converts it back. Since Java 5 the compiler inserts these conversions automatically — autoboxing and auto-unboxing — wherever a primitive is used where an object is expected, or the reverse.

2Why It Exists
Generics, collections and many APIs work only with objects: there is no List<int> or Map<String, long>. Wrappers let primitive values travel through that object-based world. They also provide a home for type-specific utilities — parsing, formatting, constants and bit operations — and allow a numeric value to be null, which is sometimes a useful way to model "no value", and often a source of bugs.

3Core Concepts
Integer
Wraps an int. Besides valueOf and intValue, it provides parseInt (to a primitive), valueOf(String) (to a wrapper), MIN_VALUE/MAX_VALUE, compare, sum/max/min (useful as method references), unsigned operations and bit utilities such as bitCount and highestOneBit.
Long
Wraps a long, with the same family of methods as Integer. Note that Long and Integer are unrelated classes: Long.valueOf(1).equals(Integer.valueOf(1)) is false, because equals on wrappers requires the same class. This matters when keys of different wrapper types meet in maps.
Double
Wraps a double. It provides isNaN, isInfinite, compare and parseDouble. Its equals differs from == in two edge cases: Double.NaN equals itself as an object, and 0.0 does not equal -0.0 as an object. Double.compare follows the same rules, which is what sorting uses.
Boolean
Wraps a boolean. There are only two useful instances, Boolean.TRUE and Boolean.FALSE, and Boolean.valueOf always returns one of them. Boolean.parseBoolean returns true only for the string "true" (case-insensitive) and false for everything else, including null.
Character
Wraps a char and hosts a large set of static utilities for Unicode classification and conversion: isDigit, isLetter, isWhitespace, toUpperCase, and code-point methods such as isSupplementaryCodePoint and toChars for characters outside the Basic Multilingual Plane.
Boxing
Autoboxing compiles to a call to the wrapper's valueOf method: Integer x = 42; becomes Integer x = Integer.valueOf(42);. It happens on assignment to a wrapper or Object variable, when passing primitives to methods expecting objects, and when adding primitives to collections. The public wrapper constructors (new Integer(42)) are deprecated for removal and should never be used.
Unboxing
Auto-unboxing compiles to a call such as intValue(). It happens on assignment to a primitive variable, in arithmetic and comparisons with <, >, + and so on, and in conditions. If the wrapper reference is null, the inserted method call throws NullPointerException — on a line that often contains no visible method call at all.

Wrapper caching
valueOf does not always create a new object. Integer, Short, Long and Byte cache instances for values from -128 to 127; Character caches 0 to 127; Boolean has only two instances. So two autoboxed Integer values of 127 are the same object, and == returns true, while two autoboxed values of 128 are different objects and == returns false. Code that compares wrappers with == therefore passes tests with small numbers and fails with real data.

The upper bound of the Integer cache can be raised with -XX:AutoBoxCacheMax, but relying on that to make == work would only move the bug. The correct fix is always to compare values, not identities.
4How It Works Internally
Autoboxing and unboxing are purely compile-time transformations. For example, list.add(5); int x = list.get(0) + 1; compiles to list.add(Integer.valueOf(5)); int x = ((Integer) list.get(0)).intValue() + 1;. The cache is a static array of pre-created Integer objects inside Integer.IntegerCache, filled when the class initialises; valueOf checks the range and returns the cached element or allocates a new object.
Each wrapper is a full object. On a typical 64-bit JVM with compressed references, an Integer occupies 16 bytes, and a collection holds an additional 4-byte reference to it. Hash-based collections add an entry object per element on top. The JIT's escape analysis can eliminate some temporary boxes in hot code, but boxes stored in collections always exist.

5APIs / Features / Syntax
| Need | Use | Avoid |
|---|---|---|
| String to primitive | Integer.parseInt(s), Long.parseLong(s) | Integer.valueOf(s).intValue() |
| String to wrapper | Integer.valueOf(s) | new Integer(s) (deprecated for removal) |
| Compare two wrappers | a.equals(b), Objects.equals(a, b) | a == b |
| Compare for sorting | Integer.compare(a, b), Comparator.comparingInt | a - b (overflows) |
| Sum a list of numbers | list.stream().mapToInt(Integer::intValue).sum() | Integer total = 0; total += x in a loop |
| Nullable numeric result | OptionalInt, OptionalLong, OptionalDouble | Integer with null as a signal |
6Practical Examples
Example 1 — The cache and == trap
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b); // true — same cached object
System.out.println(c == d); // false — two different objects
System.out.println(c.equals(d)); // true — same value
Long id = 42L;
System.out.println(id.equals(42)); // false — 42 is boxed to Integer, not Long
System.out.println(id == 42); // true — id is unboxed, numbers compared
Example 2 — Mini program: an order import that meets every wrapper trap
Problem. An import job reads order rows in which the quantity may be missing and the customer ID is a Long. It totals the units per customer and then looks a customer up. The program walks into four of this topic's traps and avoids the fifth.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class OrderImport {
record Row(String sku, Integer qty, Long customer) {} // nullable
public static void main(String[] args) {
List<Row> rows = List.of(
new Row("pen", 3, 1001L), new Row("ink", null, 1001L),
new Row("pad", 2, 2002L), new Row("pen", 200, 2002L));
Map<Long, Integer> units = new HashMap<>();
List<String> problems = new ArrayList<>();
for (Row r : rows) {
if (r.qty() == null) { // check before unboxing
problems.add(r.sku() + ": missing qty");
continue;
}
int qty = r.qty(); // unboxing is now safe
units.merge(r.customer(), qty, Integer::sum);
}
System.out.println("units : " + units);
System.out.println("problems : " + problems);
System.out.println("get(1001) : " + units.get(1001)); // Integer key
System.out.println("get(1001L) : " + units.get(1001L)); // Long key
Integer a = rows.get(3).qty(), b = 200;
System.out.println("a == b : " + (a == b)
+ ", equals " + a.equals(b));
List<Integer> qtys = new ArrayList<>(List.of(3, 2, 200));
qtys.remove(Integer.valueOf(2)); // by value, not index 2
System.out.println("qtys : " + qtys);
}
}units : {2002=202, 1001=3}
problems : [ink: missing qty]
get(1001) : null
get(1001L) : 3
a == b : false, equals true
qtys : [3, 200]Why it behaves this way. The null check before int qty = r.qty() is what keeps the missing quantity from becoming a NullPointerException; without it the unboxing would throw on the "ink" row. units.get(1001) boxes 1001 to an Integer, which is never equal to a Long key, so the lookup returns null although the customer is in the map; 1001L finds it. 200 is outside the Integer cache, so two boxes of 200 are different objects and == is false while equals is true (Figure 6). Finally, remove(Integer.valueOf(2)) removes the value 2, where remove(2) would have removed the element at index 2.
Example 3 — NullPointerException without a visible method call
Map<String, Integer> stock = new HashMap<>();
stock.put("pen", 5);
int books = stock.get("book"); // NullPointerException (unboxing null)
int safe = stock.getOrDefault("book", 0); // 0
record OrderLine(String sku, Integer quantity) {}
OrderLine line = new OrderLine("pen", null);
if (line.quantity() > 0) { … } // NullPointerException in a comparisonExample 4 — Hidden boxing in a loop
Long total = 0L; // wrapper by mistake
for (long i = 0; i < 1_000_000; i++) {
total += i; // unbox, add, box a new Long every time
}
long fast = 0L; // primitive: no allocation at all
for (long i = 0; i < 1_000_000; i++) {
fast += i;
}Example 5 — Measuring the cost of accidental boxing
Problem. Example 4 says that a Long accumulator allocates a new object per step. The JVM's per-thread allocation counter shows how much, for ten million additions.
import java.lang.management.ManagementFactory;
import java.util.Locale;
public class BoxingCost {
static final com.sun.management.ThreadMXBean MX =
(com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
static Long boxedSum(int n) {
Long total = 0L;
for (long i = 0; i < n; i++) total += i; // a new Long per step
return total;
}
static long primitiveSum(int n) {
long total = 0L;
for (long i = 0; i < n; i++) total += i;
return total;
}
static void measure(String label, Runnable r) {
long bytes = MX.getCurrentThreadAllocatedBytes();
long start = System.nanoTime();
r.run();
long ms = (System.nanoTime() - start) / 1_000_000;
bytes = MX.getCurrentThreadAllocatedBytes() - bytes;
System.out.printf(Locale.ROOT, "%-5s %,13d bytes allocated, %4d ms%n",
label, bytes, ms);
}
public static void main(String[] args) {
int n = 10_000_000;
measure("Long", () -> boxedSum(n));
measure("long", () -> primitiveSum(n));
}
}Output of one run on JDK 21 (bytes and times vary with the JVM and the JIT):
Long 239,999,856 bytes allocated, 85 ms
long 0 bytes allocated, 10 msWhy it behaves this way. Each total += i unboxes the Long, adds and boxes the result with Long.valueOf, which allocates a new 24-byte object for every value outside the cache: about 240 MB of garbage for one loop, and many times slower than the primitive loop, which allocates nothing. Escape analysis in the JIT can sometimes remove such boxes, but only when the loop is compiled and the box provably does not escape; production code should not depend on it. In JFR, this pattern shows up as a hot allocation site in Long.valueOf.
Example 6 — remove(int) versus remove(Object)
List<Integer> ids = new ArrayList<>(List.of(10, 20, 30));
ids.remove(1); // removes index 1 → [10, 30]
ids.remove(Integer.valueOf(10)); // removes value 10 → [30]
Example 7 — Safe comparison in sorting
// Broken: subtraction overflows for large values of opposite sign
Comparator<Order> bad = (x, y) -> x.priority() - y.priority();
// Correct
Comparator<Order> good = Comparator.comparingInt(Order::priority);7Common Problems & Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Comparing wrappers with == | Works for small numbers, fails above 127 | equals / Objects.equals, or compare primitives |
| Unboxing a possibly-null value | NPE on a line with no method call | Null-check, getOrDefault, or primitive fields |
| Wrapper accumulator in a loop | High allocation rate, GC pressure | Primitive local variables |
| Long key looked up with an Integer | Map lookup returns null | Use consistent key types (1L, not 1) |
| new Integer(…) | Deprecation warnings; no caching | Integer.valueOf |
| Subtraction in comparators | Wrong order due to overflow | Integer.compare / Comparator.comparingInt |
| Nullable wrapper fields in entities without reason | NPEs spread through code | Primitive if a value is mandatory; Optional at API edges |
| A ternary that mixes int and Integer | The Integer branch is unboxed; a null throws NullPointerException | Make both branches Integer, or check for null first (Q13) |
| Boolean.parseBoolean for user input | "yes", "Y" and "1" all become false without any error | Validate the accepted values explicitly |
| Raising -XX:AutoBoxCacheMax to make == work | The bug moves to larger values and other JVMs | Compare values with equals or as primitives |
8Performance & Production Considerations
- Boxed collections of numbers cost roughly four to five times the memory of primitive arrays and increase GC work. For large numeric datasets use
int[]/long[], primitive streams (IntStream,LongStream), or primitive-specialised collection libraries. - Accidental boxing in hot loops shows up as high allocation rates in JFR or an allocation profiler. It is usually a one-line fix.
- Caches keyed by boxed numbers (
Map<Long, Customer>) are normal and fine; the concern is very large maps of millions of entries, where entry and box overhead dominate. - Wrapper objects are immutable and thread-safe; sharing them is always safe.
9Architecture & Design Considerations
Using a wrapper instead of a primitive is also a modelling decision about whether a value can be absent:
| Situation | Recommended type | Reason |
|---|---|---|
| Mandatory numeric field (quantity, amount in minor units) | Primitive (int, long) | Cannot be null; cheaper |
| Optional value in a JPA entity or DB column that allows NULL | Wrapper (Integer, Long) | Must represent SQL NULL |
| Optional value returned from a method | OptionalInt / Optional<T> | Makes absence explicit to the caller |
| API payload (JSON) | Wrapper, with validation | Distinguish "missing" from 0; validate at the boundary |
| Large numeric data in memory | Primitive arrays or primitive streams | Memory and GC efficiency |
10Interview Questions & Answers
What are wrapper classes and why do they exist?
Immutable classes that hold one primitive value each: Byte, Short, Integer, Long, Float, Double, Character and Boolean. They exist so primitives can be used where objects are required — generics, collections, reflection — and to host parsing and utility methods.
What are autoboxing and auto-unboxing?
Automatic conversions inserted by the compiler: boxing calls valueOf to turn a primitive into a wrapper, and unboxing calls methods such as intValue to turn a wrapper back into a primitive.
Why does Integer a = 127, b = 127; a == b print true, but the same with 128 prints false?
Autoboxing uses Integer.valueOf, which returns cached instances for -128 to 127. Both 127s are the same cached object, so identity comparison is true. 128 is outside the cache, so two separate objects are created and == compares different identities. Use equals to compare values.
What is the difference between Integer.parseInt and Integer.valueOf?
parseInt returns a primitive int. valueOf returns an Integer, using the cache for small values. Use parseInt when you need a primitive, to avoid a needless box.
How can int x = map.get(key); throw NullPointerException?
map.get returns an Integer; assigning it to an int inserts intValue(). If the key is absent, get returns null and the unboxing call throws. Use getOrDefault, check for null, or keep the value as a wrapper.
Why does Long.valueOf(1).equals(1) return false?
The argument 1 is autoboxed to Integer, and Long.equals returns true only for another Long with the same value. Wrappers of different types are never equal, even with the same numeric value.
A batch job's GC time jumped after a refactoring changed a local long total to Long total. Why?
Each += now unboxes the Long, adds, and boxes a new Long object — millions of short-lived allocations per run. The fix is to keep the accumulator primitive. Allocation profiling with JFR shows this pattern clearly.
Why is subtraction a bad way to implement compareTo for integers?
x - y overflows when the values are large and of opposite sign, producing the wrong sign and therefore the wrong order. Integer.compare(x, y) or Comparator.comparingInt avoid overflow.
When should an entity or DTO field be int versus Integer?
Use a primitive when the value is mandatory and 0 is a legitimate value; use a wrapper when the value can genuinely be absent, for example a nullable database column or an optional JSON field that must be distinguished from zero. Validate and convert at the boundary so the domain model uses the most precise type.
How would you design an in-memory cache of fifty million numeric IDs?
Avoid Map<Long, …> or Set<Long> at that size: boxing and entry objects could cost gigabytes. Use sorted long[] arrays with binary search, primitive-specialised collections, bitmaps (such as Roaring bitmaps) or an off-heap/store-backed solution, depending on update pattern. Measure footprint with a heap profiler before and after.
Your team repeatedly ships bugs from == on wrappers and null unboxing. What do you change at organisation level?
Make it a tooling problem rather than a review problem: enable static-analysis rules for reference equality on boxed types and possible null unboxing, adopt nullability annotations on public APIs, set conventions for primitive versus wrapper fields at each layer, and add these cases to the team's coding standard with examples. Track the rule violations in CI so they cannot be merged.
What does this program print?
public class WrapperQuiz {
public static void main(String[] args) {
double nan = Double.NaN;
Double boxedNan = nan;
System.out.println((nan == nan) + " " + boxedNan.equals(nan));
Double zero = 0.0, minusZero = -0.0;
System.out.println((0.0 == -0.0) + " " + zero.equals(minusZero));
System.out.println(Boolean.parseBoolean("YES") + " "
+ Boolean.parseBoolean("True"));
}
}It prints false true, true false, false true. On primitives, == follows IEEE 754: NaN is unequal to itself and 0.0 equals -0.0. Double.equals compares the bit patterns instead, so NaN equals NaN and 0.0 does not equal -0.0, which keeps hash-based collections consistent. Boolean.parseBoolean accepts only "true", ignoring case, and returns false for everything else, including "YES".
What does this program print?
import java.util.ArrayList;
import java.util.List;
public class TernaryQuiz {
public static void main(String[] args) {
List<Integer> ids = new ArrayList<>(List.of(5, 6, 7));
int index = 1;
Integer value = 1;
ids.remove(index);
ids.remove(value);
System.out.println(ids);
Integer missing = null;
try {
Integer result = ids.isEmpty() ? 0 : missing;
System.out.println(result);
} catch (NullPointerException e) {
System.out.println("NullPointerException");
}
}
}It prints [5, 7] and then NullPointerException. ids.remove(index) with an int calls remove(int index) and removes 6, the element at index 1; ids.remove(value) with an Integer calls remove(Object) and finds no element equal to 1, so nothing changes. In the ternary, one branch is int and the other Integer, so the result type is int and missing is unboxed even though the result is assigned to an Integer.
How does Integer.valueOf decide whether to return a cached object, and can the cache be changed?
Integer.valueOf(int) checks whether the value is between -128 and the cache's upper bound and, if so, returns an element of a static array in Integer.IntegerCache that was filled when the class was initialised; otherwise it allocates a new Integer. The lower bound is fixed by the specification, while the upper bound can be raised with -XX:AutoBoxCacheMax=<n> (or the system property java.lang.Integer.IntegerCache.high). Short, Byte, Long and Character have fixed caches. Since autoboxing calls valueOf, these rules decide whether == on boxed values happens to be true.
Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.
Key Takeaways
- Wrappers are immutable objects around primitives; autoboxing uses valueOf, unboxing uses xxxValue().
- -128 to 127 are cached, so == on wrappers is unreliable — always compare values.
- Unboxing null throws NullPointerException, often on lines with no visible call.
- Boxed numbers cost several times the memory of primitives; avoid them in large data and hot loops.
- Choosing primitive or wrapper is a nullability decision at each boundary.