Java Formatter class

Introduction

To create a formatted string, use the format() method.

The most commonly used version is shown here:

Formatter format(String fmtString , Object ... args) 

The fmtSring has two types of items.

  • characters that are copied to the output buffer
  • format specifiers that format the arguments.

A format specifier begins with a percent sign followed by the format conversion specifier.

All format conversion specifiers consist of a single character.

For example, the format specifier for floating-point data is %f.

In general, the number of arguments is the same with the number of format specifiers.

The format specifiers and the arguments are matched in order from left to right.

For example, consider this fragment:

Formatter fmt = new Formatter();  
fmt.format("Formatting %s is easy %d %f", "with Java", 10, 123.6); 

This sequence creates a Formatter that contains the following string:


// Demonstrate Currency.
import java.util.Formatter;

public class Main {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();  
    String s = fmt.format("Formatting %s is easy %d %f", "with Java", 10, 123.6).toString();
    System.out.println(s);//ww  w.  j  a  v  a2  s  .c  om
    fmt.close();
  }
}



PreviousNext

Related