Kingdom: Code Quality
Poor code quality leads to unpredictable behavior. From a user's perspective that often manifests itself as poor usability. For an attacker it provides an opportunity to stress the system in unexpected ways.
Code Correctness: Erroneous String Compare
Abstract
Strings should be compared with the
equals()
method, not ==
or !=
.Explanation
This program uses
Example 1: The following branch will never be taken.
The
==
or !=
to compare two strings for equality, which compares two objects for equality, not their values. Chances are good that the two references will never be equal.Example 1: The following branch will never be taken.
if (args[0] == STRING_CONSTANT) {
logger.info("miracle");
}
The
==
and !=
operators will only behave as expected when they are used to compare strings contained in objects that are equal. The most common way for this to occur is for the strings to be interned, whereby the strings are added to a pool of objects maintained by the String
class. Once a string is interned, all uses of that string will use the same object and equality operators will behave as expected. All string literals and string-valued constants are interned automatically. Other strings can be interned manually be calling String.intern()
, which will return a canonical instance of the current string, creating one if necessary.References
[1] Standards Mapping - Common Weakness Enumeration CWE ID 597
desc.structural.java.code_correctness_erroneous_string_compare