Reference equality test on strings¶
ID: java/reference-equality-on-strings
Kind: problem
Security severity:
Severity: warning
Precision: medium
Tags:
- quality
- reliability
- correctness
- external/cwe/cwe-597
Query suites:
- java-security-and-quality.qls
Click to see the query in the CodeQL repository
Comparing two String objects using == or != compares object identity, which may not be intended. The same sequence of characters can be represented by two distinct String objects.
Recommendation¶
To see if two String objects represent the same sequence of characters, you should usually compare the objects by using their equals methods.
Example¶
With the following definition, headerStyle is compared to the empty string using ==. This comparison can yield false even if headerStyle is the empty string, because it compares the identity of the two string objects rather than their contents. For example, if headerStyle was initialized by an XML parser or a JSON parser, then it might have been created with code like String.valueOf(buf,start,len). Such code will produce a new string object every time it is called.
void printHeader(String headerStyle) {
if (headerStyle == null || headerStyle == "") {
// No header
return;
}
// ... print the header
}
With the following definition, headerStyle is tested using the equals method. This version will reliably detect whenever headerStyle is the empty string.
void printHeader(String headerStyle) {
if (headerStyle == null || headerStyle.equals("")) {
// No header
return;
}
// ... print the header
}
References¶
Java API Specification: String.equals(), String.intern().
Java Language Specification: 15.21.3 Reference Equality Operators == and !=, 3.10.5 String Literals , 15.28 Constant Expressions.
Common Weakness Enumeration: CWE-597.