org.sonar.l10n.java.rules.squid.S1698.html Maven / Gradle / Ivy
The newest version!
Using the equality (==
) and inequality (!=
) operators to compare two objects does not check to see if they have the same values. Rather it checks to see if both object references point to exactly the same object in memory. The vast majority of the time, this is not what you want to do. Use the .equals() method to compare the values of two objects or to compare a string object to a string literal.
Compliant Solution
String str1 = "blue";
String str2 = "blue";
String str3 = str1;
if (str1.equals(str2))
{
System.out.println("they're both 'blue'"); // this prints
}
if (str1.equals("blue"))
{
System.out.println("they're both 'blue'"); // this prints
}
if (str1 == str3)
{
System.out.println("they're the same object"); // this still prints, but it's probably not what you meant to do
}
See
- MITRE, CWE-595 - Comparison of Object References Instead of Object Contents
- CERT, EXP03-J - Do not use the equality operators when comparing values of boxed primitives
© 2015 - 2025 Weber Informatics LLC | Privacy Policy