Formatter Argument Index And Reuse

Reference arguments out of order with %2$ indices, repeat the previous value with the %< flag, and fail loudly on indices beyond the argument list.

JavaCli Tooling

Code

snippet
import java.util.Formatter;

public class PositionalFormat {

    public static void main(String[] args) {
        // 显式索引:%2$ 引第 2 个实参,同一实参可被多次引用
        System.out.println("row: " + String.format("%2$-6s|%1$04d|", 42, "SKU"));

        // 重排:输出顺序跟格式串走,与实参顺序无关(javadoc 官方示例)
        System.out.println("reorder: " + String.format("%4$s %3$s %2$s %1$s", "a", "b", "c", "d"));

        // 相对索引 '<':复用上一个格式说明符刚消费的实参
        System.out.println("repeat: " + String.format("%s %s %<s %<s", "a", "b", "c", "d"));

        // 混用三种索引:普通 %s 的隐式序号独立于显式/相对索引计数
        System.out.println("mixed: " + String.format("%2$s %s %<s %s", "a", "b", "c", "d"));

        // 索引越界直接抛 MissingFormatArgumentException,而不是安静输出 null
        try {
            String.format("%9$s", "a");
        } catch (Exception e) {
            System.out.println("missing arg: " + e.getClass().getSimpleName());
        }
    }
}

Inside the snippet

All of the logic lives in the class PositionalFormat and the function main.

What to watch for

  • Self-sufficient by design — there is no registry and no lockfile entry.

Using it

Signature: public static void main(String[] args)

The file’s output announces each step as it happens: row:, reorder:, repeat:.

The key statements, annotated

String.format("%9$s", "a");

Interactive Tools for This Topic

FAQ

What does Formatter Argument Index And Reuse print when run?
Running the file directly is enough — expect labeled output lines such as `row:`, `reorder:`, `repeat:`.