Core Java

Format Output in a Table Format Using System.out

Formatting output in a table-like structure is essential for displaying data in a clear and organized way. Java provides several methods to help format output, each with unique advantages. Let us delve into understanding how to use Java to format output in a table structure using the System.out methods.

1. Using String Concatenation

The simplest way to format output is by using string concatenation to organize columns. However, this method can lead to inconsistent formatting if not carefully managed. Let’s clarify this with an example:

package com.init;

public class TableFormatExample {
    public static void main(String[] args) {
        System.out.println("ID" + "    " + "Name" + "    " + "Score");
        System.out.println("-------------------------");
        System.out.println("1" + "     " + "Alice" + "   " + "85");
        System.out.println("2" + "     " + "Bob" + "     " + "90");
    }
}

1.1 Code Explanation and Output

In the TableFormatExample class, the main method is defined, which serves as the entry point of the program. Within this method, several System.out.println statements are used to output text to the console.

The first line of output prints the headers of the table: “ID”, “Name”, and “Score”. These headers are separated by spaces to create a clear distinction between them. The second line prints a series of dashes, which acts as a visual separator between the headers and the data rows that follow.

Subsequent lines print individual records, each consisting of an ID, a name, and a score. For instance, the first record shows “1” for ID, “Alice” for Name, and “85” for Score, while the second record shows “2” for ID, “Bob” for Name, and “90” for Score. Each piece of data is also separated by spaces to maintain alignment and readability.

The code produces the following output in the IDE console.

ID    Name    Score
-------------------------
1     Alice   85
2     Bob     90

2. Using printf() method

The printf() method provides a powerful way to control formatting. You can specify field widths, alignments, and types, making it ideal for creating tables. Let’s clarify this with an example:

package com.init;

public class TableFormatExample {
    public static void main(String[] args) {
        System.out.printf("%-5s %-10s %-5s%n", "ID", "Name", "Score");
        System.out.printf("%-5s %-10s %-5s%n", "----", "----------", "-----");
        System.out.printf("%-5d %-10s %-5d%n", 1, "Alice", 85);
        System.out.printf("%-5d %-10s %-5d%n", 2, "Bob", 90);
    }
}

2.1 CodeExplanation and Output

The provided Java code defines a class named TableFormatExample, which contains a main method that serves as the entry point for execution. This program demonstrates how to format and print tabular data to the console using the printf method, which allows for more precise control over the output format compared to println.

Within the main method, the first line uses System.out.printf to print the headers of the table: “ID,” “Name,” and “Score.” The format specifiers %-5s, %-10s, and %-5s indicate that each string should be left-aligned within a field of specified width—5 characters for ID, 10 for Name, and 5 for Score. The %n at the end of the format string ensures that a new line is printed after this output.

The second line similarly prints a separator line with dashes, using the same format specifiers to maintain alignment with the headers. This creates a clear visual distinction between the header and the data rows.

The next two lines print individual records using the same formatting approach. The first record shows “1” for ID, “Alice” for Name, and “85” for Score, while the second record displays “2” for ID, “Bob” for Name, and “90” for Score. Here, %-5d is used for integers (ID and Score), ensuring they are also left-aligned within their respective fields.

The code produces the following output in the IDE console.

ID    Name       Score
----  ---------- -----
1     Alice      85   
2     Bob        90

3. Using String.format() method

The String.format() method is similar to printf() but returns a formatted string, making it useful for cases where the formatted string needs to be reused or further processed. Let’s clarify this with an example:

package com.init;

public class TableFormatExample {
    public static void main(String[] args) {
        String header = String.format("%-5s %-10s %-5s", "ID", "Name", "Score");
        String separator = String.format("%-5s %-10s %-5s", "----", "----------", "-----");
        String row1 = String.format("%-5d %-10s %-5d", 1, "Alice", 85);
        String row2 = String.format("%-5d %-10s %-5d", 2, "Bob", 90);

        System.out.println(header);
        System.out.println(separator);
        System.out.println(row1);
        System.out.println(row2);
    }
}

3.1 Code Explanation and Output

The provided Java code defines a class named TableFormatExample, which contains the main method that serves as the program’s entry point. This program demonstrates how to format and print tabular data to the console using the String.format method, allowing for flexible string formatting.

In the main method, the first line creates a formatted string for the table header using String.format. The format specifiers %-5s, %-10s, and %-5s are used to specify that the strings “ID,” “Name,” and “Score” should be left-aligned within fields of 5, 10, and 5 characters, respectively. This ensures that the output is neatly aligned when printed.

The second line constructs a separator string, which visually distinguishes the header from the data rows. It uses the same format specifiers to maintain alignment with the header.

Next, two rows of data are created using similar formatting. The first row, represented by row1, includes the values “1” for ID, “Alice” for Name, and “85” for Score. The second row, represented by row2, includes “2” for ID, “Bob” for Name, and “90” for Score. Here, %d is used for integers (ID and Score), while %s is used for strings (Name), ensuring proper formatting.

Finally, each of these formatted strings—header, separator, row1, and row2—is printed to the console using System.out.println. This results in a structured output that resembles a table, making it easy to read and interpret.

The code produces the following output in the IDE console.

ID    Name       Score
----  ---------- -----
1     Alice      85   
2     Bob        90

4. Using StringBuilder

StringBuilder is effective for building large strings efficiently. Although it doesn’t provide inherent formatting capabilities, it can be combined with String.format() to generate formatted table data. Let’s clarify this with an example:

package com.init;

public class TableFormatExample {
    public static void main(String[] args) {
        StringBuilder table = new StringBuilder();
        table.append(String.format("%-5s %-10s %-5s%n", "ID", "Name", "Score"));
        table.append(String.format("%-5s %-10s %-5s%n", "----", "----------", "-----"));
        table.append(String.format("%-5d %-10s %-5d%n", 1, "Alice", 85));
        table.append(String.format("%-5d %-10s %-5d%n", 2, "Bob", 90));

        System.out.print(table.toString());
    }
}

4.1 Code Explanation and Output

The provided Java code defines a class named TableFormatExample, which contains the main method, serving as the entry point for execution. This program demonstrates how to format and print tabular data to the console using a StringBuilder to efficiently build the output.

In the main method, a StringBuilder object named table is instantiated. This object will be used to construct the formatted table as a single string. The first line appends a formatted string for the table header using String.format. The format specifiers %-5s, % -10s, and % -5s indicate that the strings “ID”, “Name”, and “Score” should be left-aligned within fields of 5, 10, and 5 characters, respectively.

The second line appends a separator string, which visually distinguishes the header from the data rows. It uses the same format specifiers to ensure alignment with the header.

Two additional lines create formatted strings for individual data rows. The first row contains “1” for ID, “Alice” for Name, and “85” for Score, while the second row contains “2” for ID, “Bob” for Name, and “90” for Score. The format specifiers %d are used for integers (ID and Score), while %s is used for strings (Name).

Finally, the constructed table is printed to the console using System.out.print(table.toString()). This results in a neatly formatted output that resembles a table, making it easy to read and interpret.

The code produces the following output in the IDE console.

ID    Name       Score
----  ---------- -----
1     Alice      85   
2     Bob        90

5. Using ASCII Table

ASCII Table use symbols such as pipes (|) and dashes (-) to create visually structured tables. They are often used for command-line outputs, enhancing readability. Let’s clarify this with an example:

package com.init;

public class TableFormatExample {
    public static void main(String[] args) {
        System.out.println("+-----+----------+-------+");
        System.out.println("| ID  | Name     | Score |");
        System.out.println("+-----+----------+-------+");
        System.out.printf("| %-3d | %-8s | %-5d |%n", 1, "Alice", 85);
        System.out.printf("| %-3d | %-8s | %-5d |%n", 2, "Bob", 90);
        System.out.println("+-----+----------+-------+");
    }
}

ASCII characters are added manually to form borders and separators. The printf() method is used to format each cell, ensuring proper alignment within each column. The code produces the following output in the IDE console.

ID    Name       Score
----  ---------- -----
1     Alice      85   
2     Bob        90

6. Conclusion

Java offers several ways to format output in a table format. String Concatenation is suitable for basic needs, while printf() and String.format() provide control over alignment and precision. StringBuilder is ideal for dynamically generated tables, and ASCII formatting adds visual appeal to command-line outputs. Each method has its strengths, allowing developers to choose the most appropriate one based on their specific requirements.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button