Formatter class

In this chapter you will learn:

  1. What is Formatter class for
  2. Formatting Basics

What is Formatter class for

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.

Formatting Basics

The most commonly used format function is:

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

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


The format specifiers and the arguments are matched in order from left to right. For example, consider this fragment:

import java.util.Formatter;
//from  ja  v  a  2  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); 

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 are the specifiers for Java Formatter class
Home » Java Tutorial » String


    Java String type
    Java String Concatenation
    Java String Creation
    Java String Compare
    Java String Search
    Java String and char array
    Java String Conversion
    String trim, length, is empty, and substring
    String replace


    StringBuffer class
    StringBuffer Insert and Append
    StringBuffer length and capacity
    StringBuffer char operation
    StringBuffer Operations
    Search within StringBuffer
    StringBuffer to String


    StringBuilder insert and append
    StringBuilder length and capacity
    StringBuilder get,delete,set char
    StringBuilder delete, reverse
    StringBuilder search with indexOf and lastIndexOf
    StringBuilder to String

String Format

    Formatter class
    Format Specifier
    Format String and characters
    Format integer value
    Format decimal
    Scientific notation format
    Format octal and hexadecimal value
    Format date and time value
    Escape Formatter
    Minimum Field Width
    Specifying Precision
    Format Flags
    Uppercase Option
    Formatter Argument Index
    Align left and right
    Left and right padding a string

String Format Utilities

    Abbreviate string
    Caplitalize a string
    Uncapitalize a string
    Utility class for right padding
    Left padding
    Centers a String
    Transforms words