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
double quotes around the equals sign, using a StringBuilder (see Putting Strings Together
with StringBuilder ) or a MessageFormat (see Formatting Messages with MessageFormat ), or
using String.format() (see Printing with Formatter and printf ). Of course in this simple
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.
Search WWH ::




Custom Search