Home > Java > javaTutorial > Java Integer Comparison: When Should You Use == vs. equals()?

Java Integer Comparison: When Should You Use == vs. equals()?

DDD
Release: 2024-12-21 06:41:10
Original
291 people have browsed it

Java Integer Comparison: When Should You Use == vs. equals()?

Integer Equality in Java: Unraveling the == vs. equals Quandary

Java's introduction of autoboxing in version 1.5 allowed for convenient interchanging of primitive types like int and their corresponding wrapper classes such as Integer. However, a recent observation has raised questions about the validity of using == for comparison of Integer values.

Consider the following code:

Integer cdiCt = ...;
Integer cdsCt = ...;
...
if (cdiCt != null & cdiCt != cdsCt)
    mismatch = true;
Copy after login

Surprisingly, this code would sometimes set mismatch to true even when the values of cdiCt and cdsCt were equal. Using a breakpoint in Eclipse revealed that both Integer values were equal to 137, yet the conditional expression evaluated to false.

Changing the conditional to use equals() instead:

if (cdiCt != null & cdiCt != null & !cdiCt.equals(cdsCt))
Copy after login

resolved the issue. This raises the question: is it still not advisable to use == for comparing two Integer values?

The answer lies in the Java Virtual Machine (JVM) caching of Integer values. To improve performance, the JVM caches Integer values between -128 and 127. This means that when you compare two Integer values within this range using ==, they will only be equal if they refer to the same cached instance.

However, if the values fall outside this range or are not autoboxed, they will be treated as distinct objects. This can lead to unexpected behavior, as demonstrated in the provided example.

Therefore, it is generally not recommended to rely on == for comparing Integer values, especially when they may exceed the cached range or if precision is critical. Instead, using equals() is the safer approach to ensure reliable equality comparisons.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template