Java Reference
In-Depth Information
System.out.println("The answer is "+val);
“But what if val is not a String ?” we hear you asking. Don't worry, the
Java compiler is smart enough to know, that when you are adding with a
String argument it must convert the other argument to a String , too. So for
any Object , it will implicitly call its toString() method. For any primitive
type (e.g., int or boolean ), the compiler will convert it to a String , too.
The third of the three output methods, printf() , sounds very familiar
to C/C++ programmers, but be warned:
• It is only available in Java 5.0 7 and after.
• It is similar but not identical to the C/C++ version.
Perhaps the most significant enhancement to printf() is its additional
syntax for dealing with internationalization. It's all well and good to translate
your String s to a foreign language, but in doing so you may need to change
the word order and thus the order of the arguments to printf() . For example,
the French tend to put the adjective after rather than before the noun (as we do
in English). We say “the red balloon” and they say “le balloon rouge.” If your
program had String s for adjective and noun, then a printf() like this:
String format = "the %s %s\n";
System.out.printf(format, adjective, noun);
wouldn't work if you translate just the format String :
String format = "le %s %s\n";
System.out.printf(format, noun, adjective);
You'd like to be able to do the translation without changing the code in your
program. 8 With the Java version of printf() , there is syntax for specifying
which argument corresponds to which format field in the format string. It uses
7. Remember, you'll need the -source 5.0 option on the command line.
8. Java has good support for internationalization, another topic for which we don't have the
time. The ability to translate the strings without otherwise modifying the program is a crucial
part to internationalization, and the printf() in Java 5.0 is certainly a help in this regard. In
a similar vein, the Eclipse IDE, covered in Chapter 10, includes a feature to take all string
constants and convert them to external properties at a stroke, making internationalization much
easier to do.
Search WWH ::




Custom Search