StringBuilder Char Constructor
ID |
java.stringbuilder_char_constructor |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
reliability |
Description
Reports a StringBuilder or StringBuffer constructor invoked with a single char argument: a character literal such as 'x', or a variable whose declared type is char.
Rationale
Neither StringBuilder nor StringBuffer defines a constructor that takes a char. The argument is silently widened to int, so the single-argument constructor resolves to StringBuilder(int) / StringBuffer(int), which sets the initial capacity, not the initial content. The builder starts empty, holding the character’s UTF-16 code point as a capacity hint instead of the character itself.
// Bad - creates an EMPTY builder with capacity 81 (the code point of 'Q'), not "Q"
StringBuilder sb = new StringBuilder('Q');
Remediation
Pass a String when the intent is initial content, or convert an existing char value with String.valueOf().
// Good - starts with the character as content
StringBuilder sb = new StringBuilder("Q");
// Good - converts a char variable to its String representation first
char gradeLetter = 'Q';
StringBuilder sb2 = new StringBuilder(String.valueOf(gradeLetter));