Under the Hood / Part 8YOUTUBE PLAYER LOADS ON PLAYWhy 127 == 127 but 128 != 128
Why

Why 127 == 127 but 128 != 128 in Java (Integer Cache) | Under the Hood

Under the Hood25 Nov 20261:21Open on YouTube

In this lesson

In Java, 127 == 127 is true, but 128 == 128 is false. Same code, different answer. Here's why.

→ Integer is an object, not a primitive. Assigning a number boxes it → Behind the scenes, the compiler calls Integer.valueOf() → valueOf caches Integer objects from -128 to 127 → 127 twice → the same cached object → == is true → 128 → a new object each time → == is false → The fix: equals(), or compare plain ints. Long, Short and Byte have the same cache

Under the Hood: how Java really works.

Instagram: @thecodestormdev

Keep going

More Shorts.