Looking for java Keywords? Try Ask4Keywords

Java Language Aligning strings in console


Example

The method PrintWriter.format (called through System.out.format) can be used to print aligned strings in console. The method receives a String with the format information and a series of objects to format:

String rowsStrings[] = new String[] {"1", 
                                     "1234", 
                                     "1234567", 
                                     "123456789"};

String column1Format = "%-3s";    // min 3 characters, left aligned
String column2Format = "%-5.8s";  // min 5 and max 8 characters, left aligned
String column3Format = "%6.6s";   // fixed size 6 characters, right aligned
String formatInfo = column1Format + " " + column2Format + " " + column3Format;

for(int i = 0; i < rowsStrings.length; i++) {
    System.out.format(formatInfo, rowsStrings[i], rowsStrings[i], rowsStrings[i]);
    System.out.println();
}

Output:

1   1          1
1234 1234    1234
1234567 1234567 123456
123456789 12345678 123456

Using format strings with fixed size permits to print the strings in a table-like appearance with fixed size columns:

String rowsStrings[] = new String[] {"1", 
                                     "1234", 
                                     "1234567", 
                                     "123456789"};

String column1Format = "%-3.3s";  // fixed size 3 characters, left aligned
String column2Format = "%-8.8s";  // fixed size 8 characters, left aligned
String column3Format = "%6.6s";   // fixed size 6 characters, right aligned
String formatInfo = column1Format + " " + column2Format + " " + column3Format;

for(int i = 0; i < rowsStrings.length; i++) {
    System.out.format(formatInfo, rowsStrings[i], rowsStrings[i], rowsStrings[i]);
    System.out.println();
}

Output:

1   1             1
123 1234       1234
123 1234567  123456
123 12345678 123456

Format strings examples

  • %s: just a string with no formatting
  • %5s: format the string with a minimum of 5 characters; if the string is shorter it will be padded to 5 characters and right aligned
  • %-5s: format the string with a minimum of 5 characters; if the string is shorter it will be padded to 5 characters and left aligned
  • %5.10s: format the string with a minimum of 5 characters and a maximum of 10 characters; if the string is shorter than 5 it will be padded to 5 characters and right aligned; if the string is longer than 10 it will be truncated to 10 characters and right aligned
  • %-5.5s: format the string with a fixed size of 5 characters (minimum and maximum are equals); if the string is shorter than 5 it will be padded to 5 characters and left aligned; if the string is longer than 5 it will be truncated to 5 characters and left aligned