Java Reference
In-Depth Information
PrintWriter pw
=
new
new
PrintWriter
(
System
.
out
);
pw
.
println
(
"The answer is "
+
myAnswer
+
" at this time."
);
One caveat with this string concatenation is that if you are appending a bunch of things, and
a number and a character come together at the front, they are added before concatenation due
to the precedence rules. So don't do this:
int
int
i
= ...;
System
.
out
.
println
(
i
+
'='
+
" the answer."
);
Given that
i
is an integer, then
i + '=
' (
i
added to the equals sign, which is of the numeric
type
char
) is a valid
numeric
expression, which will result in a single value of type
int
. If
the variable
i
has the value 42, and the character
=
in a Unicode (or ASCII) code chart has
the value 61, this prints:
103 the answer.
The wrong value and no equals sign! Safer approaches include using parentheses, using
example you could just move the
=
to be part of the string literal, but the example was
chosen to illustrate the problem of arithmetic on
char
values being confused with string con-
tatenation.
Printing with Formatter and printf
Problem
You want the ease of use that the
java.util.Formatter
class brings to simple printing
tasks.
Solution
Use
Formatter
for printing values with fine-grained control over the formatting.