Java Wrapper Classes and Autoboxing
Java's wrapper classes Integer, Double, Boolean and friends explained: why ArrayList<int> isn't allowed, how autoboxing and unboxing work, the == trap and the Integer cache, NullPointerException on unboxing, parseInt and other static helpers, MIN_VALUE pitfalls, and performance costs.
kvi5hnuCode Sprout team member10 min readOn this page
Java has two kinds of values: primitives (int, double, boolean, …) and objects. Sometimes you need a primitive value as an object, for example to store numbers in an ArrayList. For that, every primitive type has a class counterpart called a wrapper. This article covers the wrappers, the automatic conversions between primitives and wrappers (autoboxing and unboxing), and the surprising pitfalls that come with them.
The Wrapper Classes
| Primitive | Wrapper |
|---|---|
int | Integer |
long | Long |
short | Short |
byte | Byte |
double | Double |
float | Float |
char | Character |
boolean | Boolean |
The first six (the numeric ones) extend the common superclass Number, which has methods such as intValue(), longValue() and doubleValue().
Wrapper objects are immutable: you can't change the wrapped value after construction. The wrapper classes are also final, so you can't subclass them.
Why Wrappers? Generic Collections
Suppose you want an array list of integers. The type argument in angle brackets can't be a primitive type: ArrayList<int> isn't allowed. That's where Integer comes in:
var list = new ArrayList<Integer>();
Autoboxing and Unboxing
Adding an int to an ArrayList<Integer> is easy. The call
list.add(3);
is automatically translated into
list.add(Integer.valueOf(3));
This conversion is called autoboxing. (You might think "autowrapping" would be more consistent; the "boxing" metaphor was borrowed from C#.)
Conversely, when you assign an Integer to an int, it's automatically unboxed. The compiler translates
int n = list.get(i);
into
int n = list.get(i).intValue();
Boxing and unboxing even work in arithmetic expressions. You can apply the increment operator to a wrapper variable:
Integer n = 3;
n++;
The compiler inserts instructions to unbox the object, increment the value, and box a new object (wrappers are immutable, so the old one isn't changed).

Boxing and unboxing are a courtesy of the compiler, not the virtual machine. The compiler inserts the valueOf and xxxValue calls when it generates bytecode, and the JVM simply executes them.
The Pitfalls
In most cases, you get the illusion that primitives and their wrappers are the same thing. They differ considerably in a few situations.
1. Identity: never compare wrappers with ==
== applied to wrapper objects tests whether they're the same object, not whether they have the same value. This comparison will probably fail:
Integer a = 1000;
Integer b = 1000;
if (a == b) . . . // false (usually)
To make it more confusing, a Java implementation may wrap commonly occurring values into shared objects, so the comparison might succeed. In fact, the language specification requires that boxing these values always yields the same object:
booleanvalues,bytevalues,charvalues up to127,shortandintvalues between −128 and 127.
So with Integer c = 100, d = 100;, c == d is guaranteed to be true. With 1000 it's false on a default JVM. (The cache's upper bound can even be raised with -XX:AutoBoxCacheMax.) Code whose behavior depends on the size of a number is a bug waiting to happen.
The remedy: compare wrapper objects with equals (or unbox them first):
a.equals(b) // true
a.intValue() == b.intValue()
Objects.equals(a, b) // null-safe
2. Don't use the constructors
The wrapper constructors such as new Integer(1000) have been deprecated for removal since Java 16 (JEP 390):
warning: [removal] Integer(int) in Integer has been deprecated and marked for removal
Use Integer.valueOf(1000), which can return cached objects, or simply rely on autoboxing: Integer a = 1000;.
3. Unboxing null throws NullPointerException
Wrapper references can be null, so auto-unboxing can throw a NullPointerException:
Integer n = null;
System.out.println(2 * n); // throws NullPointerException
This often comes from Map<String, Integer> lookups: int count = map.get("missing"); throws if the key isn't present. Use map.getOrDefault(key, 0).
4. Mixed types in conditional expressions
If you mix Integer and Double in a conditional expression, the Integer is unboxed, promoted to double, and boxed into a Double:
Integer pieces = 7;
Double weight = 0.25;
boolean byCount = true;
System.out.println(byCount ? pieces : weight); // prints 7.0, not 7
5. Overloading surprises
Boxing changes which overload is chosen. List<Integer> has remove(int index) and remove(Object o), so list.remove(1) removes the element at index 1, while list.remove(Integer.valueOf(1)) removes the value 1.
6. Hidden boxing in loops
Long sum = 0L;
for (int k = 0; k < 1_000_000; k++) sum += k; // creates up to a million Long objects
Declaring sum as Long instead of long silently boxes on every iteration. Use primitives for accumulators.
Wrappers as a Home for Static Methods
You'll often see the number wrappers for another reason. Java's designers found them a convenient place for basic static methods, such as converting strings of digits to numbers:
int x = Integer.parseInt(s);
This has nothing to do with Integer objects. parseInt is a static method, and Integer was simply a good place to put it.
Some of the most important Integer methods (the other number classes have corresponding ones):
| Method | Description |
|---|---|
int intValue() | Returns the value as an int (overrides Number.intValue) |
static String toString(int i) | Returns i in base 10 |
static String toString(int i, int radix) | Returns i in the given base, e.g. Integer.toString(255, 2) → "11111111" |
static int parseInt(String s) / parseInt(String s, int radix) | Parses digits in base 10 or the given base; throws NumberFormatException for bad input |
static Integer valueOf(String s) / valueOf(String s, int radix) | Like parseInt, but returns an Integer (possibly cached) |
static Integer valueOf(int i) | Boxes i, using the cache for −128 to 127 |
static int compare(int x, int y) | Negative, zero or positive, without overflow risk |
static String toHexString(int i), toBinaryString, toOctalString | Unsigned representations |
static int sum, max, min | Handy as method references (Integer::sum) |
Other wrappers have equivalents: Double.parseDouble, Long.parseLong, Boolean.parseBoolean, and Character has character tests such as isDigit, isLetter and isWhitespace.
MIN_VALUE and MAX_VALUE
Every wrapper defines constants. For the integral types, MIN_VALUE and MAX_VALUE are the smallest and largest values: Integer.MIN_VALUE is -2147483648 and Integer.MAX_VALUE is 2147483647. A typical use:
int largest = Integer.MIN_VALUE; // replaced with the first larger value
while (in.hasNextInt()) largest = Math.max(largest, in.nextInt());
Wrappers Can't Make Parameters Modifiable
Some people think wrappers let you write methods that modify numeric arguments. They don't. As shown in the pass-by-value article, this can't work:
public static void triple(int x) { // won't work
x = 3 * x; // modifies the local variable
}
Using Integer doesn't help either:
public static void triple(Integer x) { // won't work either
x = 3 * x; // creates a new Integer; the caller's object is unchanged
}
Integer objects are immutable: the value inside can't change. Return the new value instead. (If you truly need a mutable integer holder, there's AtomicInteger, or a one-element array, but returning a value is cleaner.)
Everything Together
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static void main(String[] args) {
var list = new ArrayList<Integer>();
list.add(3); // autoboxing: list.add(Integer.valueOf(3))
int n = list.get(0); // unboxing: list.get(0).intValue()
Integer count = 3;
count++; // unbox, increment, box
System.out.println(n + " " + count);
Integer a = 1000, b = 1000;
Integer c = 100, d = 100;
System.out.println((a == b) + " " + a.equals(b)); // identity vs value
System.out.println((c == d) + " " + c.equals(d)); // cached -128..127
Integer missing = null;
try {
System.out.println(2 * missing);
} catch (NullPointerException ex) {
System.out.println("NPE while unboxing");
}
Integer i1 = 1;
Double x = 2.0;
System.out.println(true ? i1 : x); // prints 1.0
System.out.println(Integer.parseInt("42") + Integer.parseInt("ff", 16));
System.out.println(Integer.toString(255, 2) + " " + Integer.toHexString(255));
System.out.println(Integer.MIN_VALUE + " " + Integer.MAX_VALUE);
System.out.println(Double.MIN_VALUE + " " + -Double.MAX_VALUE);
System.out.println(Integer.valueOf("123") + 1);
try {
Integer.parseInt("1_000");
} catch (NumberFormatException ex) {
System.out.println(ex.getMessage());
}
System.out.println(Integer.compare(3, 7) + " " + Integer.sum(3, 7) + " " + Character.isDigit('7'));
List<Integer> nums = new ArrayList<>(List.of(10, 20, 30));
nums.remove(Integer.valueOf(10));
nums.remove(0);
System.out.println(nums);
Number num = 3.75; // boxed to Double
System.out.println(num.intValue() + " " + num.getClass().getSimpleName());
// performance: sum with boxed vs primitive accumulator
Long boxed = 0L;
long primitive = 0;
for (int k = 0; k < 1000; k++) { boxed += k; primitive += k; }
System.out.println(boxed + " " + primitive);
}
}
3 4
false true
true true
NPE while unboxing
1.0
297
11111111 ff
-2147483648 2147483647
4.9E-324 -1.7976931348623157E308
124
For input string: "1_000"
-1 10 true
[30]
3 Double
499500 499500
(The false in the second line is what a default JVM prints. The language only guarantees caching for −128 to 127, which is exactly why you shouldn't use ==.)
Common questions
Why can't generics use primitive types?
Generics are implemented with type erasure: at runtime, a List<T> holds Object references. Primitives aren't objects, so they must be boxed. Project Valhalla aims to allow generics over value types and primitives in the future. Until then, use primitive arrays or IntStream-style streams for large numeric data.
Is autoboxing slow? Each boxing of a value outside the cache creates an object, and unboxing follows a reference. In a hot loop with millions of iterations, that can make code several times slower and creates garbage. For ordinary code it doesn't matter. Avoid wrapper types for counters, accumulators and large numeric arrays.
What does Integer.valueOf("08") give?
8. valueOf(String) and parseInt always use base 10 and accept leading zeros. Only Java source code literals treat a leading 0 as octal. Use Integer.parseInt(s, 16) or Integer.decode("0x1F") to parse other bases.
Are wrapper objects safe as HashMap keys?
Yes. They are immutable and implement equals and hashCode by value. Be careful with mixed types, though: Integer.valueOf(1).equals(Long.valueOf(1)) is false, so a Map<Long, ...> looked up with an int key boxes it to Integer and finds nothing.
Should I use Optional<Integer> or OptionalInt?
For methods that may return no number, OptionalInt, OptionalLong and OptionalDouble avoid boxing. Primitive streams return them: IntStream.max() gives an OptionalInt. Optional<Integer> is fine when you are already working with boxed values.
Summary
- Each primitive type has an immutable, final wrapper class:
Integer,Long,Short,Byte,Double,Float,Character,Boolean. The numeric ones extendNumber. - Generic types need wrappers:
ArrayList<Integer>, notArrayList<int>. That convenience costs memory and speed. - The compiler autoboxes (
Integer.valueOf) and unboxes (intValue) automatically, even in arithmetic. - Compare wrappers with
equals, not==. Only values from −128 to 127 (and a few others) are guaranteed to be cached. - Unboxing
nullthrowsNullPointerException. MixedInteger/Doubleconditionals promote todouble. Avoid the deprecated constructors. - Wrappers host static utilities:
parseInt,toString(i, radix),compare,MIN_VALUE/MAX_VALUE.Double.MIN_VALUEis the smallest positive double. - Wrappers can't be used to modify parameters; they're immutable.
Practice Questions
Why doesn't new ArrayList<int>() compile, and what do you use instead?
Type arguments must be reference types. Use new ArrayList<Integer>(); autoboxing makes adding and reading int values convenient.
Integer x = 127, y = 127; Integer p = 128, q = 128; What do x == y and p == q print?
x == y is true, since values from −128 to 127 are guaranteed to be cached and share one object. p == q is false on a default JVM: two different objects. Use equals to compare values.
Map<String, Integer> stock = new HashMap<>(); int n = stock.get("apples"); What happens?
get returns null for a missing key, and unboxing null into an int throws a NullPointerException. Use stock.getOrDefault("apples", 0).
What's wrong with this code for finding the maximum of doubles? double max = Double.MIN_VALUE; for (double v : values) max = Math.max(max, v);
Double.MIN_VALUE is the smallest positive double (about 4.9E-324), so the result is wrong if all values are negative. Start with Double.NEGATIVE_INFINITY or -Double.MAX_VALUE.
Why does Integer.parseInt("1,234") throw an exception, and how would you parse user input like that?
parseInt accepts only an optional sign and digits, with no grouping separators. Use NumberFormat.getInstance(Locale.US).parse("1,234") or a Scanner with an appropriate locale.
Previous: Java ArrayList: Generic Array Lists Explained
Next: Java Varargs: Methods with a Variable Number of Arguments
Related reading
- Java Object Class and the equals Method
- Java final Classes and Methods, Casting, instanceof Patterns and protected Access
- Java Polymorphism and Dynamic Binding: How Method Calls Are Resolved
- Java Inheritance: Superclasses, Subclasses and Method Overriding
- Java Class Design Hints: Writing Clean, Maintainable Classes

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.