CodeQL documentation

Useless toString on String

ID: java/useless-tostring-call
Kind: problem
Security severity: 
Severity: recommendation
Precision: high
Tags:
   - maintainability
Query suites:
   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

There is no need to call toString on a String because it just returns the object itself. From the Java API Specification entry for String.toString():

public String toString()

This object (which is already a string!) is itself returned.

Recommendation

Do not call toString on a String object.

Example

The following example shows an unnecessary call to toString on the string name.

public static void main(String args[]) {
	String name = "John Doe";
	
	// BAD: Unnecessary call to 'toString' on 'name'
	System.out.println("Hi, my name is " + name.toString());
	
	// GOOD: No call to 'toString' on 'name'
	System.out.println("Hi, my name is " + name);
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy