Some instructors will remember that Pascal and C++ allow the programmer to easily specify the field width and precision of numbers for output. Java 5.0 includes a printf method that greatly eases the formatting of numeric and other output in Java. Like the methods print and println, printf can be used to send output either to the terminal window or to text files.
The parameters of printf consist of a format string and a set of data values. A format string contains information about how to format each datum to be output. Here are some examples of the use of printf:
double doubleVal = 3.516;
int intVal = 35;
// Output 35, right-justified in 10 columns
System.out.printf("%10d", intVal);
// Output 3.52, right-justified in 10 columns (with 2 figures of precision)
System.out.printf("%10.2f", doubleVal);
// Sequence the previous two outputs, followed by a newline
System.out.printf("%10d%10.2f%n", intVal, doubleVal);
// Output a two-column table of the first 10 powers of 2, with
// the exponent left-justfied in 3 columns and the power right-justfied
// in 10 columns
for (int expo = 1; expo <= 10; expo++)
System.out.printf("%-3d%10d%n", expo, Math.pow(2, expo));
The String method format can be used to build a formatted string. The information passed to format is similar to the information passed to printf. Here is the powers of 2 example using format instead of printf:
// Output a two-column table of the first 10 powers of 2, with
// the exponent left-justfied in 3 columns and the power right-justfied
// in 10 columns
for (int expo = 1; expo <= 10; expo++){
String str = String.format("%-3d%10d", expo, Math.pow(2, expo));
System.out.println(str);
}