
org.sonar.l10n.java.rules.squid.S1698.html Maven / Gradle / Ivy
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.
Noncompliant Code Sample
String str1 = "blue";
String str2 = "blue";
String str3 = str1;
if (str1 == str2)
{
System.out.println("they're both 'blue'"); // this doesn't print because the objects are different
}
if (str1 == "blue")
{
System.out.println("they're both 'blue'"); // this doesn't print because the objects are different
}
if (str1 == str3)
{
System.out.println("they're the same object"); // this prints
}
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
}
Exception
Comparing two instances of the Class
object will not raise an issue.
Class c;
if(c == Integer.class) { //No issue raised
}
See
- MITRE, CWE-595 - Comparison of Object References Instead of Object Contents
© 2015 - 2025 Weber Informatics LLC | Privacy Policy