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.
Code
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
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.