Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Why is this loop slow, and what else could go wrong with boxed types?

Java
Long sum = 0L;
for (long i = 0; i < n; i++) {
sum += i;
}

sum is a Long, so every sum += i unboxes the current value, adds, and boxes the result into a new Long object; Long.valueOf only caches -128 to 127, so almost every iteration allocates. Changing sum to a primitive long fixes it. Boxed types also bring two classic bugs: == compares references, which only works by accident inside the cache range, and unboxing a null throws a NullPointerException.

Why this question is asked

Autoboxing makes primitives and their wrapper classes look interchangeable, and most of the time that convenience is harmless. In a hot loop or in comparisons, though, the difference between long and Long is the difference between a register and a heap object. Interviewers ask this question to check that we can see the hidden work the compiler inserts, and that we know the bugs that come with it. In this answer, we will look at what the compiler generates for the loop, see why it allocates, fix it, and then go through the two other traps of boxed types, including the follow-up about Integer a = 1000.

1A Quick Recap of Boxing

Java has primitive types such as int and long, which hold a value directly, and wrapper classes such as Integer and Long, which are objects on the heap that hold one value each. Autoboxing is the compiler converting a primitive to its wrapper automatically, by calling Long.valueOf. Unboxing is the reverse, calling longValue().

Wrapper objects are immutable. A Long can never change its value, so any arithmetic on a Long produces a brand new Long. Keep that in mind, because it is the whole story of the slow loop.

2What the Compiler Generates for the Loop

The source looks like simple arithmetic, but sum += i on a Long cannot modify the object. The compiler rewrites it into an unbox, an add and a box.

Java
Long sum = 0L;
for (long i = 0; i < n; i++) {
sum += i;
}
// What javac actually emits for the loop body:
sum = Long.valueOf(sum.longValue() + i); // unbox, add, box a new Long
Step throughOne iteration with a boxed sum
  1. Read suma reference to a Long on the heap
  2. Unboxsum.longValue()
  3. Add iplain long arithmetic
  4. Is the result in -128..127?
    YesReuse a cached LongNoAllocate a new Long
  5. Store the new reference in sumthe old Long becomes garbage

5 steps in order. Play them, or step through them one at a time.

After the first 16 iterations, the right-hand branch is taken every time.

So each iteration calls longValue(), adds, and then calls Long.valueOf. Long.valueOf returns a cached object only for values from -128 to 127. The running sum leaves that range after the first few iterations (0 + 1 + ... + 16 = 136), so from then on every iteration allocates a new 16 to 24 byte object. For n of one billion that is about one billion objects and many gigabytes of garbage, plus the loop carries a dependency through memory instead of a register. The JIT can sometimes remove boxing through escape analysis, but a box carried around a loop like this is a case it often cannot handle, so we should not rely on it.

3The Fix: Use a Primitive

The fix is one word. With a primitive long, the JIT keeps sum in a CPU register and the loop is a handful of instructions per iteration, often unrolled.

Java
long sum = 0L; // primitive
for (long i = 0; i < n; i++) {
sum += i; // register add, no allocation
}
// Illustrative, n = 1_000_000_000:
// Long sum: several seconds and gigabytes of allocation
// long sum: well under a second, zero allocation

The same applies to collections. A List<Long> of a million numbers holds a million objects plus the list's array of references. If the code is numeric and hot, a long[] or a LongStream avoids all of it. For example, LongStream.range(0, n).sum() computes the same result without boxing.

4Trap 1: Comparing Boxed Values With ==

For objects, == compares references, asking whether both sides are the same object, not whether they hold the same value. With boxed numbers this becomes confusing, because of the cache we just met. This answers the follow-up question directly.

Java
Integer a = 127, b = 127;
System.out.println(a == b); // true: both come from the Integer cache
Integer c = 1000, d = 1000;
System.out.println(c == d); // false: two different Integer objects
System.out.println(c.equals(d)); // true: same value
int e = 1000;
System.out.println(c == e); // true: one side is primitive, so c is unboxed

Integer c = 1000 compiles to Integer.valueOf(1000). Since 1000 is outside the default cache range of -128 to 127, each call creates a new object, so c == d compares two different references and prints false. The upper bound of the Integer cache can be raised with -XX:AutoBoxCacheMax, and then the same code could print true, which shows that the result depends on configuration rather than on the values. The Long, Short and Byte caches are fixed at -128 to 127. The safe rule is to compare boxed values with equals or Objects.equals, or to unbox them deliberately.

5Trap 2: Unboxing a Null

A wrapper variable can be null, and a primitive cannot. When the compiler inserts an unboxing call on a null reference, the result is a NullPointerException on a line that does not appear to call any method.

Java
Map<String, Long> totals = new HashMap<>();
long t = totals.get("missing"); // NullPointerException: get returns null, then longValue()
Long maybe = null;
long x = flag ? maybe : 0L; // NullPointerException when flag is true:
// the ternary has type long, so maybe is unboxed
long safe = totals.getOrDefault("missing", 0L); // 0

The ternary case surprises people the most. Because one branch is a primitive, the whole expression has the primitive type, so the Long branch is unboxed even though we only wanted to pass the value along. Since Java 14, helpful NullPointerException messages name the method that failed, such as a call to longValue() on a null value, which makes these bugs much easier to spot.

6Follow-up questions

What does Integer a = 1000, b = 1000; a == b return, and why?

It returns false with default settings. The literals are boxed with Integer.valueOf, which only returns shared cached instances for -128 to 127. 1000 is outside that range, so a and b are two different objects, and == compares references. a.equals(b) returns true. If the JVM runs with a larger -XX:AutoBoxCacheMax, the result can become true, which is exactly why code must never depend on it.

Why does Java cache small values at all?

Small numbers are extremely common, for example loop counters, status codes and small quantities, so sharing one immutable object for each of them saves a lot of allocation. The Java Language Specification requires that boxing values between -128 and 127 returns the same object every time.

Is boxing always slow?

No. A boxed value created once per request costs almost nothing, and the JIT can remove boxing in some inlined code. It matters in hot loops, large collections of numbers and code that compares boxed values with ==.

7Conclusion

In this answer, we saw that sum += i on a Long compiles to an unbox, an add and a Long.valueOf call, and because Long caches only -128 to 127, nearly every iteration allocates a new object. Changing sum to a primitive long removes the allocation and keeps the value in a register. We also met the two classic bugs of boxed types: == compares references and only works by accident within the cache range, which is why Integer 1000 == 1000 is false, and unboxing a null, including inside a ternary, throws a NullPointerException.

What to say in the interviewAbout 80 seconds aloud

Open with

The loop is slow because sum is a Long, which is an immutable object. sum += i compiles to sum = Long.valueOf(sum.longValue() + i), so every iteration unboxes, adds and boxes the result.

Then, if they want more

Long.valueOf only returns cached objects for minus 128 to 127, and the running sum leaves that range after about sixteen iterations, so from then on every iteration allocates a new Long. For a billion iterations that is a billion objects and gigabytes of garbage, and the JIT cannot reliably eliminate a box carried around a loop like this.

The fix is to declare sum as a primitive long, which stays in a register and allocates nothing. Boxed types have two other traps. First, == on two Integers or Longs compares references, not values.

It seems to work for small numbers because of the cache, so Integer a = 127, b = 127 gives true, but Integer a = 1000, b = 1000 gives false with default settings, so we use equals or Objects.equals.

Second, unboxing null throws a NullPointerException, for example long t = map.get(key) for a missing key, or a ternary where one branch is primitive and the other is a null Long.

About this answer

Last updated
12 November 2026
Versions it names
Java 14
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Why is this loop slow, and what else could go wrong with boxed types?": https://scrivio-interview-library.netlify.app/java/java-performance/fed6255430/