Useless toString on String¶
ID: java/useless-tostring-callKind: problemSecurity severity: Severity: recommendationPrecision: highTags: - quality - maintainability - useless-codeQuery suites: - java-security-and-quality.qls
Click to see the query in the CodeQL repository
There is no need to calltoString on aString because it just returns the object itself. From the Java API Specification entry forString.toString():
publicStringtoString()
This object (which is already a string!) is itself returned.
Recommendation¶
Do not calltoString on aString object.
Example¶
The following example shows an unnecessary call totoString on the stringname.
publicstaticvoidmain(Stringargs[]){Stringname="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¶
Java API Specification:String.toString().