org.sonar.l10n.java.rules.java.S1317.html Maven / Gradle / Ivy
This rule raises an issue when the StringBuilder
or StringBuffer
constructor is called with a single character as an
argument.
Why is this an issue?
When a developer uses the StringBuilder
or StringBuffer
constructor with a single character as an argument, the likely
intention is to create an instance with the character as the initial string value.
However, this is not what happens because of the absence of a dedicated StringBuilder(char)
or StringBuffer(char)
constructor. Instead, StringBuilder(int)
or StringBuffer(int)
is invoked, which results in an instance with the provided
int
value as the initial capacity of the StringBuilder
or StringBuffer
.
The reason behind this behavior lies in the automatic widening of char
expressions to int
when required. Consequently,
the UTF-16 code point value of the character (for example, 65
for the character 'A'
) is interpreted as an int
to specify the initial capacity.
How to fix it
If the argument is a char
literal, use a string literal instead:
StringBuffer foo = new StringBuffer('x'); // Noncompliant, replace with String
StringBuffer foo = new StringBuffer("x"); // Compliant
If the argument is it is a non-literal char
expression, convert it to String
using the String.valueOf()
method:
StringBuffer foo(char firstChar) {
return new StringBuffer(firstChar); // Noncompliant
}
StringBuffer foo(char firstChar) {
return new StringBuffer(String.valueOf(firstChar)); // Compliant
}
Resources
Documentation
Articles & blog posts