int size = 7; System.out.printf("Perfect: %8.3f %n", size );
No. The format specifier does not match the data type. The error will be detected at run-time.
public class LeftJust { public static void main ( String[] args ) { double x = 12.34, y = -6.95, z = 1024; System.out.printf("x:%8.3f, y:%8.3f, z:%8.3f%n", x, y, z); // default right justification System.out.printf("x:%-8.3f, y:%-8.3f, z:%-8.3f%n%n", x, y, z); // left justification int a = 12, b = 12345, c = -1234567; System.out.printf("a:%10d; b:%10d; c:%10d%n", a, b, c); // default right justification System.out.printf("a:%-10d; b:%-10d; c:%-10d%n", a, b, c); // left justification } }
To left justify values, put a minus sign (-) after the percent sign. This works for all format specifiers. The output of the above program:
x: 12.340, y: -6.950, z:1024.000 x:12.340 , y:-6.950 , z:1024.000 a: 12; b: 12345; c: -1234567 a:12 ; b:12345 ; c:-1234567
What do you suspect the following prints?
String wizard = "Gandalf"; System.out.printf("|%15s|%n", wizard ); System.out.printf("|%-15s|%n", wizard );