Java Reference
In-Depth Information
The last and most subtle bug is that the expression
new StringBuffer('M')
probably does not do
what you think it does. You may not be familiar with the
StringBuffer(char)
constructor, and
with good reason: It does not exist. There is a parameterless constructor, one that takes a
String
indicating the initial contents of the string buffer and one that takes an
int
indicating its initial
capacity. In this case, the compiler selects the
int
constructor, applying a
widening primitive
conversion
to convert the
char
value
'M'
into the
int
value
77
[JLS 5.1.2]. In other words,
new
StringBuffer('M')
returns an empty string buffer with an initial capacity of 77. The remainder of
the program appends the characters
a
,
i
, and
n
to the empty string buffer and prints out its contents,
which are always
ain
.
To avoid this kind of problem,
use familiar idioms and APIs whenever possible. If you must use
unfamiliar APIs, read the documentation carefully.
In this case, the program should have used
the common
StringBuffer
constructor that takes a
String
.
This corrected version of the program fixes all three bugs, printing
Pain
,
Gain
, and
Main
with equal
likelihood:
import java.util.Random;
public class Rhymes {
private static Random rnd = new Random();
public static void main(String[] args) {
StringBuffer word = null;
switch(rnd.nextInt(
3
)) {
case 1:
word = new StringBuffer(
"P"
);
break;
case 2:
word = new StringBuffer(
"G"
);
break;
default:
word = new StringBuffer(
"M"
);
break;
Search WWH ::
Custom Search