Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Character passed to StringBuffer or StringBuilder constructor

ID: java/string-buffer-char-initKind: problemSecurity severity: Severity: errorPrecision: very-highTags:   - quality   - reliability   - correctnessQuery suites:   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

Passing a character to the constructor ofStringBuffer orStringBuilder is probably intended to insert the character into the newly created buffer. In fact, however, the character value is converted to an integer and interpreted as the buffer’s initial capacity, which may yield unexpected results.

Example

The following example shows a class representing points in two-dimensional Cartesian coordinates. ThetoString method uses aStringBuffer to construct a human-readable representation of the form(x,y), wherex andy are the point’s coordinates.

However, the opening parenthesis is passed to theStringBuffer constructor as character literal. Instead of being used to initialise the buffer’s contents, the character is converted to the integer value 40 and interpreted as the buffer’s initial capacity. Thus, the string representation returned bytoString will be missing the opening parenthesis. (Note that passing a character toappend, on the other hand, is unproblematic.)

classPoint{privatedoublex,y;publicPoint(doublex,doubley){this.x=x;this.y=y;}@OverridepublicStringtoString(){StringBufferres=newStringBuffer('(');res.append(x);res.append(", ");res.append(y);res.append(')');returnres.toString();}}

Recommendation

If the character used to initialize the buffer is a character literal, simply replace it with the corresponding string literal. So, in our example, replacenewStringBuffer('(') withnewStringBuffer("("). If the character is not a literal value, use methodString.valueOf to convert it to a string.

References


[8]ページ先頭

©2009-2025 Movatter.jp