Java Formatter Class

In this chapter you will learn:

  1. What is Java Format Class
  2. Syntax for format method
  3. Note for format method
  4. Example - format method

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;
/* ww  w  .  j  ava2 s  .c  o  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.

Next chapter...

What you will learn in the next chapter:

  1. What is Format Specifier
  2. What are the specifiers for Java Formatter class
  3. Example - Java Format Specifier
  4. Example - Unknown Format Conversion Exception
  5. How to use %n and %% specifiers to escape new line and percentage
  6. Example - The following code combines the %n, %d %% to display file copy progress information
Home »
  Java Tutorial »
    Java Langauge »
      Java Data Format
Java Formatter Class
Java Format Specifier
Java Format Specifier Uppercase
Java Format Precision
Java Format Flags
Java Format Justifying Output
Java Format Negative and Positive
Java Format Line up Space
Java Format Parentheses
Java Format Zero Padding
Java Format Comma
Java Format Alternate Conversion
Java Format Argument Index
Java Format date time
Java Format Date