YAS -SER
YAS -SER

Reputation: 25

Why does == work for small integers but not for larger ones in Java?

I've noticed a peculiar behavior in Java when comparing Integer objects using the == operator. Specifically, it seems to work as expected for small integer values but fails for larger ones. Here is an example to illustrate the issue:

Integer a = 127;
Integer b = 127;
System.out.println(a == b); // Output: true
Integer c = 128;
Integer d = 128;
System.out.println(c == d); // Output: false

In the first comparison (a == b), the result is true, but in the second comparison (c == d), the result is false. From what I understand, == should check for reference equality, so why does it behave differently for these values?

Could someone explain why this discrepancy occurs and how Java handles integer comparisons under the hood? Additionally, what is the best practice for comparing Integer values in Java to avoid such pitfalls?

Upvotes: 0

Views: 99

Answers (0)

Related Questions