/* this program demonstrates formatted output using printf */ public class FormattingExamples { public static void main(String[] args) { int x = 1234567890; double y = 123.456789; String z = "abcdefghij"; System.out.printf("%d\n", x); // outputs x exactly: 1234567890 System.out.printf("%5d\n", x); // 5 is too small, outputs x exactly: 1234567890 System.out.printf("%12d\n", x); // adds 2 blanks, the number is right justified: bb1234567890 (b means blank) System.out.printf("%20d\n", x); // adds 8 blanks: bbbbbbbb1234567890 System.out.printf("%-20d\n", x); // adds 8 blanks but to the right, so we don't see them: 1234567890bbbbbbbb System.out.printf("%-20d%20d\n", x, x); // outputs x and 8 blanks then 8 blanks and x: 1234567890 1234567890 System.out.println("\n\n"); System.out.printf("%f\n", y); // outputs y exactly: 123.456789 System.out.printf("%e\n", y); // outputs y in scientific notation: 1.234568e+02 System.out.printf("%5.1f\n", y); // outputs y to 1 decimal point: 123.5 System.out.printf("%3.1f\n", y); // 3 is too small, so does the same as 5.1: 123.5 System.out.printf("%10.3f\n", y); // 10 total characters including the . with 3 to the right of the . gives bbb123.457 (10 total characters, notice the fractional part rounds up) System.out.printf("%-10.2f%10.2f\n", y, y); // Outputs: 123.46 123.46 System.out.println("\n\n"); System.out.printf("%s\n", z); // outputs z exactly: abcdefghij System.out.printf("%12s\n", z); // outputs z with 2 extra blanks on the left: bbabcdefghij System.out.printf("%-12s\n", z); // left justifies so the 2 blanks are on the right (not visible): abcdefghijbb System.out.printf("%-12s%12s\n", z, z); // outputs z twice with 4 spaces between: abcdefghij abcdefghij System.out.printf("%5s\n", z); // 5 is too small, get all of z: abcdefghij } }