Java Formatter Class

Description

Formatter class outputs the formatted output. It can format numbers, strings, and time and date. It operates in a manner similar to the C/C++ printf() function.

Syntax

The most commonly used format function is:


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

Note

The fmtSring consists characters that are copied to the output buffer and the format specifiers.

A format specifier begins with a percent sign followed by the format conversion specifier. For example, the format specifier for floating-point data is

%f

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

Example

For example, consider this fragment:


import java.util.Formatter;
/*w  w w . j av a2 s  .  co  m*/
public class Main {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    fmt.format("%s gap filler %d %f", "Astring", 10, 12.3); 
    System.out.println(fmt.out());
  }
}

The output:

In this example, the format specifiers, %s, %d, and %f, are replaced with the arguments that follow the format string. %s is replaced by "Astring", %d is replaced by 10, and %f is replaced by 12.3. %s specifies a string, and %d specifies an integer value. %f specifies a floating-point value. All other characters are simply used as-is.





















Home »
  Java Tutorial »
    Data Format »




Java Formatter
Java Number Formatter