Format Specifier

In this chapter you will learn:

  1. What are the specifiers for Java Formatter class

Format specifier in details

The format() method accepts a wide variety of format specifiers. When an uppercase specifier is used, then letters are shown in uppercase. Otherwise, the upper- and lowercase specifiers perform the same conversion. The following table shows the format specifiers:

Format SpecifierConversion Applied
%a %AFloating-point hexadecimal
%b %BBoolean
%cCharacter
%dDecimal integer
%h %HHash code of the argument
%e %EScientific notation
%fDecimal floating-point
%g %GUses %e or %f, whichever is shorter
%oOctal integer
%nInserts a newline character
%s %SString
%t %TTime and date
%x %XInteger hexadecimal
%%Inserts a % sign

If the argument doesn't match the type-checks, an IllegalFormatException is thrown.

import java.util.Formatter;
// ja  v  a  2  s  .c om
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.toString());
    System.out.println(fmt); 
  }
}

The output:

You can obtain a reference to the underlying output buffer by calling out(). It returns a reference to an Appendable object.

Next chapter...

What you will learn in the next chapter:

  1. How to format individual character and how to format string
  2. How to pass in two strings into the format string
Home » Java Tutorial » String

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

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

StringBuilder

    StringBuilder
    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