Java Format Argument Index

Description

Normally, format specifiers and arguments are matched in order, from left to right.

However, by using an argument index you can explicitly control which argument a format specifier matches.

An argument index immediately follows the % in a format specifier: n$, where n is the index of the desired argument, beginning with 1.

Syntax

fmt.format("%3$d %1$d %2$d", 10, 20, 30);

Example


import java.util.Formatter;
//from   ww  w.j  a  v a  2 s.c  o  m
public class Main {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();

    fmt.format("%3$d %1$d %2$d", 10, 20, 30);
    System.out.println(fmt);

  }
}

The code above generates the following result.

Example 2

Argument indexes enable you to reuse an argument without having to specify it twice.


import java.util.Formatter;
/*ww w . j  a  v a 2 s.c o  m*/
public class Main {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();

    fmt.format("%d in hex is %1$x", 255);
    System.out.println(fmt);

  }
}

The code above generates the following result.

Example 3

Relative index enables you to reuse the argument matched by the preceding format specifier.

Simply specify < for the argument index.


import java.util.Formatter;
/*from w  w w  . java2s . c  om*/
public class Main {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();

    fmt.format("%d in hex is %<x", 255);
    System.out.println(fmt);

  }

}

The code above generates the following result.

Example 4

Relative indexes are especially useful when creating custom time and date formats.

Because of relative indexing, the argument cal need only be passed once, rather than three times.


import java.util.Calendar;
import java.util.Formatter;
//w ww  .  ja  v  a 2  s.co  m
public class Main {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    Calendar cal = Calendar.getInstance();

    fmt.format("Today is day %te of %<tB, %<tY", cal);
    System.out.println(fmt);
  }
}

The code above generates the following result.

Today is day 1 of December, 2006

The code above generates the following result.





















Home »
  Java Tutorial »
    Data Format »




Java Formatter
Java Number Formatter