Java Notes

Formatted Output

Java 5 implements formatted output, eg, Ssytem.out.printf(). This concept is very familiar to old C and Fortran programmers (1968 all over again!). An introduction to it can be found in John Zukowski's article: Taming Tiger: Formatted output . Format conversion is something you need to know, and is probably preferable to using the DecimalFormat and DateFormat (SimpleDateFormat) classes.

The greatest strengths are for displaying numbers and dates.

The basic idea - a format string that describes how to convert values.

A format string contains text to put into the output and codes which describe how to covert the following arguments. Each conversion starts with the percent sign (%), and is terminated by one of the conversion code characters (eg, f, d, ...).

Two alternatives - Producing console output and producing strings

  1. Console output is done using either System.out.format(format, args) or the identical System.out.format(format, args). Neither of these adds the newline character at the end (like println() so you have to do that explicitly.
  2. String results are what you want in many cases when writing output to a file or for a GUI. Use String.format(format, args) in this case.

Example: Padding integers on left with blanks

The format() method's first parameter is a string that specifies how to convert a number. For integers you would typically use a "%" followed by the number of columns you want the integer to be right justified in, followed by a decimal integer conversion specifier "d". The second parameter would be the number you want to convert. For example,

int n = 2;
System.out.format("%3d", n);

This would print the number right-justified in three columns, that is with two blanks followed by 2.

You can put other non-% characters in front or back of the conversion specification, and they appear literally. For example,

int n = 2;
System.out.format("|%3d|\n|%3d|\n", n, 100*n);

would print

|  2|

Note the "\n" newline character to end a line.

Example: Controlling the number of places to the right of a floating-point number.

Just as "d" is the conversion code for decimal integers, "f" is the conversion code for decimal floating point numbers. The most commonly used feature is to control the number of

Complete format specification

Read the Java API documentation on the Formatter class for a specification of the format codes.