Java Notes

Formatted Output

Java 5 implements formatted output with printf(). This concept will be very familiar to C and Fortran programmers. A good introduction to it can be found in the following article by John Zukowski.

Taming Tiger: Formatted output

Some simple examples

format(). Amazingly, there was no built-in way to right justify numbers in Java until Java 5. You had to use if or while to build the padding yoursefl. Java 5 now provides the format() method (and in some cases also the equivalent printf() method from C)..

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 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 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 will simply appear literally. For example,

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

would print

|   2 |

Complete format specification

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