Column Alignment in Java Using printf:

Column Alignment in Java Using printf:

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?

  • The - (minus sign) ensures left alignment.
  • The number after % specifies the minimum width for that column.
  • This helps to create properly aligned output, especially when printing tables.


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]            
        

  • Each column is aligned, making it easy to read.
  • If data is shorter than the specified width, spaces are added to maintain alignment.
  • If data is longer than the specified width, it may get cut off or shift alignment.


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]
        

  • Here, values are aligned to the right within the column width.


Summary

  • %-10s → Left-aligns a string in a 10-character-wide field.
  • %10s → Right-aligns a string in a 10-character-wide field.
  • %n → Adds a newline.
  • This formatting makes table-like structured outputs easy to read.


Happy Coding !!!


要查看或添加评论,请登录

Sofia Nayak的更多文章

社区洞察

其他会员也浏览了