[java] Java output formatting for Strings

I was wondering if someone can show me how to use the format method for Java Strings. For instance If I want the width of all my output to be the same

For instance, Suppose I always want my output to be the same

Name =              Bob
Age =               27
Occupation =        Student
Status =            Single

In this example, all the output are neatly formatted under each other; How would I accomplish this with the format method.

This question is related to java formatting

The answer is


If you want a minimum of 4 characters, for instance,

System.out.println(String.format("%4d", 5));
// Results in "   5", minimum of 4 characters

For decimal values you can use DecimalFormat

import java.text.*;

public class DecimalFormatDemo {

   static public void customFormat(String pattern, double value ) {
      DecimalFormat myFormatter = new DecimalFormat(pattern);
      String output = myFormatter.format(value);
      System.out.println(value + "  " + pattern + "  " + output);
   }

   static public void main(String[] args) {

      customFormat("###,###.###", 123456.789);
      customFormat("###.##", 123456.789);
      customFormat("000000.000", 123.78);
      customFormat("$###,###.###", 12345.67);  
   }
}

and output will be:

123456.789  ###,###.###   123,456.789
123456.789  ###.##        123456.79
123.78      000000.000    000123.780
12345.67    $###,###.###  $12,345.67

For more details look here:

http://docs.oracle.com/javase/tutorial/java/data/numberformat.html


     @Override
     public String toString() {
          return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
     }

System.out.println(String.format("%-20s= %s" , "label", "content" ));
  • Where %s is a placeholder for you string.
  • The '-' makes the result left-justified.
  • 20 is the width of the first string

The output looks like this:

label               = content

As a reference I recommend Javadoc on formatter syntax


To answer your updated question you can do

String[] lines = ("Name =              Bob\n" +
        "Age =               27\n" +
        "Occupation =        Student\n" +
        "Status =            Single").split("\n");

for (String line : lines) {
    String[] parts = line.split(" = +");
    System.out.printf("%-19s %s%n", parts[0] + " =", parts[1]);
}

prints

Name =              Bob
Age =               27
Occupation =        Student
Status =            Single