Argument Index

Java-Argument Index

Argument Index

Formatter includes a very useful feature that lets you specify the argument to which a format specifier applies. Normally, format specifiers and arguments are matched in order, from left to right. That is, the first format specifier matches the first argument, the second format specifier matches the second argument, and so on. 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. Its general form is n$, where n is the index of the desired argument, beginning with 1. For example:

Argument Index

In this example, the first format specifier matches 50, the second matches “ABCD”, and the third matches 3.57. Thus, the arguments are used in an order other than strictly left to right. One advantage of argument indices is that they enable you to reuse an argument without having to specify it multiple time. For example:

Argument Index

In this example, the argument 47 is used by three format specifiers. There is a convenient shorthand called a relative index that enables you to reuse the argument matched by the preceding format specifier. Simply specify < for the argument index. For example:

Argument Index

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

Argument Index

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

Program

Argument Index

 

Program Source

import java.util.Formatter;
import java.util.Calendar;

public class Javaapp {

    public static void main(String[] args) {

        Formatter fmt = new Formatter();
        Calendar cl = Calendar.getInstance();
        fmt.format("%3$d--%1$s--%2$f", "ABCD", 3.57, 50);
        fmt.format("%n%d--%1$x--%1$o", 47);
        fmt.format("%n%tB--%<td--%<tY",cl);
        System.out.println(fmt);
        fmt.close();
    }
}

Leave a Comment