-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathStringBufferCharInit.qhelp
More file actions
57 lines (46 loc) · 2.34 KB
/
StringBufferCharInit.qhelp
File metadata and controls
57 lines (46 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>Passing a character to the constructor of <code>StringBuffer</code> or <code>StringBuilder</code>
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.</p>
</overview>
<example>
<p>The following example shows a class representing points in two-dimensional Cartesian coordinates.
The <code>toString</code> method uses a <code>StringBuffer</code> to construct a human-readable
representation of the form <code>(x, y)</code>, where <code>x</code> and <code>y</code> are the
point's coordinates.</p>
<p>However, the opening parenthesis is passed to the <code>StringBuffer</code> 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 by <code>toString</code> will be missing the opening parenthesis. (Note that passing a character
to <code>append</code>, on the other hand, is unproblematic.)</p>
<sample src="StringBufferCharInit.java" />
</example>
<recommendation>
<p>If the character used to initialize the buffer is a character literal, simply replace it with the
corresponding string literal. So, in our example, replace <code>new StringBuffer('(')</code> with
<code>new StringBuffer("(")</code>. If the character is not a literal value, use method
<code>String.valueOf</code> to convert it to a string.</p>
</recommendation>
<references>
<li>
J. Bloch and N. Gafter, <em>Java Puzzlers: Traps, Pitfalls, and Corner Cases</em>, Puzzle 23.
Addison-Wesley, 2005.
</li>
<li>
NetBeans IDE: <a href="https://web.archive.org/web/20210117160808/http://wiki.netbeans.org/Java_Hints">Java Hints</a>
</li>
<li>
PMD: <a href="https://pmd.github.io/latest/pmd_rules_java_errorprone.html#stringbufferinstantiationwithchar">Rule StringBufferInstantiationWithChar</a>
</li>
<li>
Java API:
<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/StringBuffer.html">StringBuffer</a>,
<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/StringBuilder.html">java.lang.StringBuilder</a>.
</li>
</references>
</qhelp>