Incorrect toString() Spelling
ID |
java.tostring_signature_correct |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
reliability |
Description
Reports methods named tostring() (lowercase 's') that were likely intended to override Object.toString().
Rationale
Java method names are case-sensitive. A method named tostring() does not override Object.toString(), so implicit string conversions (e.g., string concatenation, logging) will use the default implementation returning the class name and hash code rather than the custom representation. This is almost always a typo.
// Bad -- does not override Object.toString()
public class Account {
public String tostring() {
return "Account(" + id + ")";
}
}
Remediation
Rename the method to toString() with a capital 'S', and add the @Override annotation to catch such mistakes at compile time.
// Good
public class Account {
@Override
public String toString() {
return "Account(" + id + ")";
}
}