Column Alignment in Java Using printf:
Sofia Nayak
Certified Full Stack Developer (Caltech CTME) | Udacity Nanodegree Graduate(Google India Scholar 2018 )
The format string %-10s %-20s %-20s %-30s%n in Java is used with System.out.printf() to print tabular data in a structured and aligned way. Let's break it down:
Explanation of Each Component
%-10s %-20s %-20s %-30s%n
Each part corresponds to a format specifier that controls how the output is displayed.
Specifier Meaning % Indicates the start of a format specifier.
-10s A left-aligned string (s for string), occupying 10 character spaces.
-20s A left-aligned string, occupying 20 character spaces.
-20s Another left-aligned string, occupying 20 character spaces.
-30s A left-aligned string, occupying 30 character spaces.
%n Inserts a new line (platform-independent).
Why Use This Formatting?
Example Output
Let's say we have:
领英推荐
System.out.printf("%-10s %-20s %-20s %-30s%n", "Book ID", "Book Name", "Author Name", "Author Email");
System.out.printf("%-10d %-20s %-20s %-30s%n", 1, "Java Programming", "John Doe", "[email protected]");
System.out.printf("%-10d %-20s %-20s %-30s%n", 2, "Advanced Java", "Alice Smith", "[email protected]");
Output:
Book ID Book Name Author Name Author Email
1 Java Programming John Doe [email protected]
2 Advanced Java Alice Smith [email protected]
Alternative Without - (Right Alignment)
If we remove the -, it becomes right-aligned:
System.out.printf("%10s %20s %20s %30s%n", "Book ID", "Book Name", "Author Name", "Author Email");
System.out.printf("%10d %20s %20s %30s%n", 1, "Java Programming", "John Doe", "[email protected]");
System.out.printf("%10d %20s %20s %30s%n", 2, "Advanced Java", "Alice Smith", "[email protected]");
Output (Right-Aligned)
Book ID Book Name Author Name Author Email
1 Java Programming John Doe [email protected]
2 Advanced Java Alice Smith [email protected]
Summary
Happy Coding !!!