Java - Format Specifier Explicit Index

Introduction

When a format specifier sets an argument index explicitly, it is called explicit indexing.

An argument index is set after the % sign in a format specifier.

It is an integer in the decimal format and it ends with $.

Example

The following code uses three format specifiers: "%1$s", "%2$s", and "%3$s", which use explicit indexing.

System.out.printf("%1$s, %2$s, and %3$s", "Java", "Json", "Javascript");

Output

Java, Json, and Javascript

The following code uses explicit indexing and refer to an argument by non Ordinary index in the argument list using the index of the argument.

System.out.printf("%3$s, %1$s, and %2$s", "Json", "Javascript", "Java");

Output

Java, Json, and Javascript
  • "%3$s", refers to the third argument, "Java";
  • The second format specifier, "%1$s", refers to the first argument, "Json";
  • The third format specifier, "%2$s", refers to the second argument, "Javascript".

It is allowed to reference the same argument multiple times using explicit indexing.

You can also avoid referencing some arguments inside the format string.

In the following code, the first argument of "Json" is not referenced and the third argument of "Java" is referenced twice:

System.out.printf("%3$s, %2$s, and %3$s", "Json", "Javascript", "Java");

Output:

Java, Javascript, and Java