Nicer Output with printf


Format: System.out.printf(format, v, v, ..., v);
format: A format String that contains a format specifier for each value v to be printed, describing how to display the value.

Each format specifier:

Example:
System.out.printf("Name: %3s, Grade: %6.2f!\n", "Elvis", 93.6788);

Output:
Name: Elvis, Grade:  93.68!

Note that there is a blank space before 93.68, since the total field width for the double value is 6 (the value is right justified by default in that field).

Example:
System.out.printf("Name: %8s, Grade: %6.2f!\n", "Elvis", 93.6788);

Output:
Name:    Elvis, Grade: 93.68!

Note that the field specified for "Elvis" in this example has a minimum width of 8, and is padded on the left with blanks.




Flags in Format Specifiers


Flags can be used to change alignment and padding characters. A flag is placed right after the % sign in the format specifier.

We will consider two different flags:

1. The flag - : left-justifies the value in its field.

Example: System.out.printf("Hey, %-6s, your number is %-6d", "Kat", 312);

Output: Hey, Kat   , your number is 312




2. The flag 0: causes a numeric value to be padded with 0s instead of blank spaces.


Example: System.out.printf("%06.2f", 14.8);

Output: 014.80