Repository navigation
Quirk: Integer cache and == on boxed numbers - #101
Merged
Merged
Conversation
Test Results274 tests +8 271 ✅ +8 5s ⏱️ -1s Results for commit 421d843. ± Comparison against base commit 52ef489. This pull request skips 1 and un-skips 1 tests. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
Integer a = 127, b = 127; a == bistrue, but the same comparison fails for128Integer.valueOf, which caches-128..127, while the deprecatednew Integer(...)constructor never doesLong,ShortandByteshare the same-128..127cache,Charactercaches0..127, andDouble/Floatare never cachedequals(), not==, is the correct way to compare boxed values, and why unboxing anullreference throwsNullPointerExceptionWhy 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.valueOfJavadocQuiz
What does the following print?
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