Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot

...

Code Block
bgColor#FFcccc
public class BadComparison {
  public static void main(String[] args) {
    String one = new String("one""one");
    String two = new String("one""one");
    if(one == two)
      System.out.println("Equal""Equal"); //not printed
  }
}

Compliant Solution

...

Code Block
bgColor#ccccff
public class GoodComparison {
  public static void main(String[] args) {
    String one = new String("one""one");
    String two = new String("one""one");
    boolean result;
    if (one == null){
      result = two == null;
    }
    else{
      result = one == two || one.equals(two);
    }
   System.out.println(result);
  }
}

...

Code Block
bgColor#ccccff
public class GoodComparison {
  public static void main(String[] args) {
    String one = new String("one""one");
    String two = new String("one""one");
    boolean result;
    if (one != null){
      one = one.intern();
    }
    if (two != null){
      two = two.intern();
    }
    result = one == two;

   System.out.println(result);
  }
}

...

Wiki Markup
\[[JLS 05|AA. Java References#JLS 05]\] [Section 3.10.5, String Literals|http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.5]
\[[FindBugs 08|AA. Java References#FindBugs 08]\] ES: Comparison of String objects using == or \!=
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 595|http://cwe.mitre.org/data/definitions/595.html] ""Incorrect Syntactic Object Comparison"", [CWE ID 597|http://cwe.mitre.org/data/definitions/597.html] ""Use of Wrong Operator in String Comparison""

...

EXP02-J. Do not ignore values returned by methods            04. Expressions (EXP)            EXP04-J. Be wary of invisible implicit casts when using compound assignment operators