Skip to content

Quirk: Integer cache and == on boxed numbers - #101

Merged
mperor merged 1 commit into
masterfrom
DAILY/88-integer-cache-and-equality
Oct 24, 2026
Merged

mperor merged 1 commit into
masterfrom
DAILY/88-integer-cache-and-equality

Conversation

@mperor

@mperor mperor commented Oct 24, 2026 •

Copy link
Copy Markdown
Owner

Note: tests were not run locally. The build requires JDK 25 via the Gradle toolchain, and the foojay toolchain resolver is blocked by this environment's network policy (403 from the proxy), so JDK 25 could not be provisioned. The boxing/caching semantics in this test were manually verified under JDK 21, which are identical to JDK 25 for this feature. CI will verify. Opened as a draft until that's confirmed.

What you'll learn

  • Why Integer a = 127, b = 127; a == b is true, but the same comparison fails for 128
  • That autoboxing goes through Integer.valueOf, which caches -128..127, while the deprecated new Integer(...) constructor never does
  • That Long, Short and Byte share the same -128..127 cache, Character caches 0..127, and Double/Float are never cached
  • Why equals(), not ==, is the correct way to compare boxed values, and why unboxing a null reference throws NullPointerException

Why it matters

Relying on == for boxed numbers works by accident for small values and breaks silently once values leave the cached range — a classic source of subtle bugs in real code.

Read more

Integer.valueOf Javadoc

Quiz

What does the following print?

Integer a = 100, b = 100;
Integer c = 200, d = 200;
System.out.println((a == b) + " " + (c == d));
Answer `true false` — 100 is inside the `Integer` cache's `-128..127` range, so `a` and `b` are the same cached instance. 200 is outside it, so `c` and `d` are distinct `Integer` objects even though they hold the same value.

Closes #88

@mperor mperor added the daily Queued for the daily learning PR label Oct 24, 2026
@github-actions

Copy link
Copy Markdown

Test Results

274 tests  +8   271 ✅ +8   5s ⏱️ -1s
 79 suites +1     3 💤 ±0 
 79 files   +1     0 ❌ ±0 

Results for commit 421d843. ± Comparison against base commit 52ef489.

This pull request skips 1 and un-skips 1 tests.
pl.mperor.lab.java.design.pattern.creational.singleton.SingletonTest ‑ testLazyInitialized()
pl.mperor.lab.java.design.pattern.creational.singleton.SingletonTest ‑ testSerializationSafe()

@mperor
mperor marked this pull request as ready for review October 24, 2026 10:14
@mperor
mperor merged commit e635139 into master Oct 24, 2026
2 checks passed
@mperor
mperor deleted the DAILY/88-integer-cache-and-equality branch October 24, 2026 10:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

daily Queued for the daily learning PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Quirk: Integer cache and == on boxed numbers

2 participants