GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — Reference equality test on strings — CodeQL query help documentation

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.

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.