How to print a table of information in Java

user2704743 picture user2704743 · Sep 7, 2013 · Viewed 74.3k times · Source

I'm trying to print a table in Java and I was wondering what is the best way to do this?

I've tried printing new lines and using \t to make contents line up but it doesn't work. Is there a method which does this or a better way?

Answer

Luca Mastrostefano picture Luca Mastrostefano · Sep 7, 2013

You can use System.out.format(...)

Example:

final Object[][] table = new String[4][];
table[0] = new String[] { "foo", "bar", "baz" };
table[1] = new String[] { "bar2", "foo2", "baz2" };
table[2] = new String[] { "baz3", "bar3", "foo3" };
table[3] = new String[] { "foo4", "bar4", "baz4" };

for (final Object[] row : table) {
    System.out.format("%15s%15s%15s%n", row);
}

Result:

        foo            bar            baz
       bar2           foo2           baz2
       baz3           bar3           foo3
       foo4           bar4           baz4

Or use the following code for left-aligned output:

System.out.format("%-15s%-15s%-15s%n", row);