Home >Java >javaTutorial >Java Integer Comparison: When Does `==` Work, and When Should You Use `equals()`?

Java Integer Comparison: When Does `==` Work, and When Should You Use `equals()`?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-25 22:49:16897browse

Java Integer Comparison: When Does `==` Work, and When Should You Use `equals()`?

Integer Reference Equality vs. Value Equality

In Java, primitives like int and object wrappers like Integer are not interchangeable. The question poses a problem where Integer objects with equal int values are incorrectly compared using ==, resulting in unexpected true outcomes.

The answer lies in the caching of Integer values by the JVM. For performance reasons, the JVM reuses preallocated objects within a specific range (-128 to 127). When comparing Integer objects using ==, the JVM checks for reference equality, not value equality. For values within this cached range, reference equality implies value equality.

However, in the provided code example, the Integer values are outside this cached range, so reference equality does not guarantee value equality. Instead, equals() should be used to compare Integer values for equality.

The stackoverflow link referenced in the question's answer provides further insights into the complexities of autoboxing and why the compiler cannot always "make it just work."

In summary, while it's convenient to use == for primitives, it's crucial to understand the limitations of reference equality when dealing with object wrappers like Integer. For value equality comparisons, equals() should be used instead.

The above is the detailed content of Java Integer Comparison: When Does `==` Work, and When Should You Use `equals()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn