Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-4973

Strings and Boxed types should be compared using "equals()"

    Details

    • Type: Bug Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      5min
    • Analysis Level:
      Semantic Analysis
    • Analysis Scope:
      Main Sources, Test Sources
    • CERT:
      EXP03-J., EXP50-J.
    • CWE:
      CWE-595, CWE-597

      Description

      It's almost always a mistake to compare two instances of java.lang.String or boxed types like java.lang.Integer using reference equality == or !=, because it is not comparing actual value but locations in memory.

      Noncompliant Code Example

      String firstName = getFirstName(); // String overrides equals 
      String lastName = getLastName();
      
      if (firstName == lastName) { ... }; // Non-compliant; false even if the strings have the same value
      

      Compliant Solution

      String firstName = getFirstName();
      String lastName = getLastName();
      
      if (firstName != null && firstName.equals(lastName)) { ... };
      

      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
      • CERT, EXP50-J. - Do not confuse abstract object equality with reference equality

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                tibor.blenessy Tibor Blenessy
              • Votes:
                0 Vote for this issue
                Watchers:
                1 Start watching this issue

                Dates

                • Created:
                  Updated: