Java Formatter argument Index

Introduction

We can specify the argument to a format specifier in Java Formatter.

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

By using an argument index, we can control which argument a format specifier matches.

An argument index immediately follows the % in a format specifier.

It has the following format:

n$ 

where n is the index of the desired argument, beginning with 1.

For example, consider this example:

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

It produces this string:

30 10 20 

The argument indexes enable us to reuse an argument without having to specify it twice.

For example, consider this line:

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

It produces the following string:

255 in hex is ff 

The argument 255 is used by both format specifiers.

A relative index can reuse the argument matched by the preceding format specifier.

Use < for the argument index.

For example, the following call to format() produces the same results as the previous example:

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

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


// Use arguments indexes to simplify the 
// creation of a custom time and date format. 
import java.util.Calendar;
import java.util.Formatter;

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);//  ww w  .j  a  va2s .c  o m
    fmt.close();
  }
}



PreviousNext

Related