Java Format Specifier

Description

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.

Specifier List

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.

Example

Java Format Specifier


import java.util.Calendar;
import java.util.Formatter;
//from   www  .j  av  a2s.c om
public class Main {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();

    fmt = new Formatter();
    System.out.println(fmt.format("%s gap filler %d %f", "Astring", 10, 12.3)); 
  
  }
}

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

The code above generates the following result.

Example 2

Unknown Format Conversion Exception


import java.util.Date;
import java.util.Formatter;
/*from www.ja  v a  2 s.c  om*/
public class Main {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();

    fmt.format("%t", new Date());
    System.out.println(fmt);
  }
}

The code above generates the following result.

Example 3

The %n and %% format specifiers escape sequences. The %n inserts a newline. The %% inserts a percent sign.

You can use the standard escape sequence \n to embed a newline character. Here is an example that demonstrates the %n and %% format specifiers:


import java.util.Formatter;
//from   www  .  j  av  a  2s.  c om
public class Main {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    fmt.format("line%nline %d%% complete", 88);
    System.out.println(fmt);
  }
}

The output:

Example 4

The following code combines the %n, %d %% to display file copy progress information.


import java.util.Formatter;
//from  ww w. ja v  a2 s  . c om
public class Main {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    fmt.format("Copying file%nTransfer is %d%% complete", 88);
    System.out.println(fmt);

  }
}

The output:





















Home »
  Java Tutorial »
    Data Format »




Java Formatter
Java Number Formatter