Java - Format Specifier Relative Index

Introduction

In relative indexing, a format specifier uses the same argument that was used by the previous format specifier.

Relative indexing does not use an argument-index value. It uses '<' character as a flag in the format specifier.

A format specifier with Relative Indexing cannot be used with the first format specifier.

Example

The following code uses relative indexing:

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

Output

Java, Java, Java, Javascript, and Javascript

The format specifiers, "%1$s", "%<s", "%<s", "%2$s", and "%<s", uses two arguments: "Java" and "Javascript".

  • The first format specifier of "%1$s" uses explicit indexing to reference the first argument of "Java".
  • The second format specifier of "%<s" uses relative indexing and use the same argument, which was used by the previous format specifier, "1$s".
  • Both the first and the second format specifiers use the first argument of "Java".
  • The third format specifier of "%<s" also uses relative indexing. It will use the same argument as used by the previous format specifier (the second format specifier).
  • The fourth "%2$s" format specifier uses explicit indexing to use the second argument of "Javascript".
  • The fifth and the last format specifier of "%<s" uses relative indexing and it will use the same argument that is used by its previous format specifier (the fourth format specifier).

Quiz