...
This use of the equality operators also applies to numeric boxed types (for example, Byte, Character, Short, Integer, Long, Float, and Double), although the numeric relational operators (such as <, <=, >, and >=) produce results that match those provided for arguments of the equivalent primitive numeric types. See rule "EXP03-J. Do not use the equality operators when comparing values of boxed primitives" for more information.
Noncompliant Code Example
The reference equality operator == evaluates to true only when the values it compares reference the same underlying object. This noncompliant example declares two distinct String objects that contain the same value to be true. The references, however, are unequal because they reference distinct objects.
| Code Block | ||
|---|---|---|
| ||
public class StringComparison {
public static void main(String[] args) {
String str1 = new String("one");
String str2 = new String("one");
System.out.println(isEqual( str1, str2));
}
public static boolean isEqual(String str1, String str2) {
boolean result;
// test for null is redundant in this case, but required for full generality
if (str1 == null) {
result = str2 == null;
}
else {
result = str1 == str2;
}
return result; // false!
}
}
|
Compliant Solution (Object.equals())
This compliant solution uses the Object.equals() method when comparing string values.
| Code Block | ||
|---|---|---|
| ||
public class StringComparison {
public static boolean isEqual(String str1, String str2) {
boolean result;
// test for null is redundant in this case, but required for full generality
if (str1 == null) {
result = (str2 == null);
} else {
result = str1.equals(str2);
}
return result; // true
}
}
|
Compliant Solution (String.intern())
Reference equality behaves like abstract object equality when it is used to compare two strings that are results of the String.intern() method. This solution can be used for fast string comparisons when only one copy of each string is required.
...
- The cost of
String.intern()grows as the number of intern strings grows. Performance should be no worse than n log n, but the Java Language Specification lacks a specific performance guarantee. - Strings that have been interned become immortal: they cannot be garbage collected. This can be problematic when large numbers of strings are interned.
Exceptions
EXP01-EX0: Using reference equality in place of object equality is permitted only when the defining classes guarantee the existence of at most one object instance for each possible object value. This generally requires that instances of such classes are immutable. The use of static factory methods, rather than public constructors, facilitates instance control; this is a key enabling technique.
...
EXP01-EX1: Use reference equality to determine whether two references point to the same object.
Risk Assessment
Using reference equality to compare objects can lead to unexpected results.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
EXP01-J | low | probable | medium | P4 | L3 |
Automated Detection
The Coverity Prevent Version 5.0 BAD_EQ checker can detect instances where the == operator is being used for equality of objects when, ideally, the equal method should have been used. The == operator could consider the objects to be different whereas the equals method would consider them to be the same.
Findbugs checks this rule for type String.
Related Guidelines
CWE ID 595, "Comparison of Object References Instead of Object Contents" | |
| CWE ID 597, "Use of Wrong Operator in String Comparison" |
The Elements of Java Style | Rule 79: Use |
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="5916ae35d757d2b7-4d386967-47784156-9a319907-b4d095b5ec6ecb05c5582218"><ac:plain-text-body><![CDATA[ | [java:[FindBugs 2008 | AA. Bibliography#FindBugs 08]] | ES: Comparison of String objects using == or != | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="b9f0b836f6401166-d527a91b-412c48bf-b8119ce5-7db492d9941da3af23289bd9"><ac:plain-text-body><![CDATA[ | [java:[JLS 2005 | AA. Bibliography#JLS 05]] | [§3.10.5, "String Literals" | http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.5] | ]]></ac:plain-text-body></ac:structured-macro> |
|
...