All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.java.rules.squid.S1698.html Maven / Gradle / Ivy

There is a newer version: 8.6.0.37351
Show 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.

Noncompliant Code Example

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
}

See

  • MITRE, CWE-595 - Comparison of Object References Instead of Object Contents
  • MITRE, CWE-597 - Use of Wrong Operator in String Comparison
  • CERT, EXP03-J - Do not use the equality operators when comparing values of boxed primitives




© 2015 - 2025 Weber Informatics LLC | Privacy Policy