Java - Printf-style Formatting

Introduction

java.util.Formatter class supports printf-style formatting, which is similar to the printf() function in C programming language.

The following Using C's Printf-style Formatting in Java

Demo

import java.util.Date;

public class Main {
  public static void main(String[] args) {
    // Formatting strings
    System.out.printf("%1$s, %2$s, and %3$s %n", "Fu", "Hu", "Lo");
    System.out.printf("%3$s, %2$s, and %1$s %n", "Fu", "Hu", "Lo");

    // Formatting numbers
    System.out.printf("%1$4d, %2$4d, %3$4d %n", 1, 10, 100);
    System.out.printf("%1$4d, %2$4d, %3$4d %n", 10, 100, 1000);

    System.out.printf("%1$-4d, %2$-4d, %3$-4d %n", 1, 10, 100);
    System.out.printf("%1$-4d, %2$-4d, %3$-4d %n", 10, 100, 1000);

    // Formatting date and time
    Date dt = new Date();
    System.out.printf("Today is %tD %n", dt);
    System.out.printf("Today is %tF %n", dt);
    System.out.printf("Today is %tc %n", dt);
  }/*from   www . j  a v a  2  s. com*/
}

Result

API

System.out is an instance of the java.io.PrintStream class, which has println() and print() instance methods.

PrintStream class also has format() and printf() which can be used to write a formatted output to a PrintStream instance.

String class has a format() static method to the String class, which returns a formatted string.

The formatting behavior of the format()/printf() method of the PrintStream class and the format() static method of the String class is the same.

Formatter class does the real work which is used to format text.

The formatted text can be written to the following destinations:

  • An Appendable (e.g. StringBuffer, StringBuilder, Writer, etc.)
  • A File
  • An OutputStream
  • A PrintStream

format() method

The format() method of the Formatter class is overloaded.

Its declarations are as follows.

Formatter format(String format, Object... args)
Formatter format(Locale l, String format, Object... args)

The first version of the format() method uses the default locale for formatting.

The second version has a locale as parameter.

The format()/printf() method of the PrintStream class and String format() has the same two versions of the format() method.