|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
CWE-597: Use of Wrong Operator in String Comparison
Description Summary The product uses the wrong operator when comparing a string, such as using "==" when the equals() method should be used instead.
Extended Description In Java, using == or != to compare two strings for equality actually compares two objects for equality, not their values. Chances are good that the two references will never be equal. While this weakness often only affects program correctness, if the equality is used for a security decision, it could be leveraged to affect program security. Example 1 In the example below, two Java String objects are declared and initialized with the same string values and an if statement is used to determine if the strings are equivalent. (Bad Code) Example
Language: Java String str1 = new String("Hello"); String str2 = new String("Hello"); if (str1 == str2) { System.out.println("str1 == str2");
} However, the if statement will not be executed as the strings are compared using the "==" operator. For Java objects, such as String objects, the "==" operator compares object references, not object values. While the two String objects above contain the same string values, they refer to different object references, so the System.out.println statement will not be executed. To compare object values, the previous code could be modified to use the equals method: (Good Code) if (str1.equals(str2)) { System.out.println("str1 equals str2");
}
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Page Last Updated:
September 12, 2011
|
|
CWE is a Software Assurance strategic initiative co-sponsored by the National Cyber Security Division of the U.S. Department of Homeland Security. This Web site is sponsored and managed by The MITRE Corporation to enable stakeholder collaboration. Copyright © 2006-2012, The MITRE Corporation. CWE, CWSS, CWRAF, and the CWE logo are trademarks of The MITRE Corporation. Contact cwe@mitre.org for more information. |
|||



