Java - What is the output: Mix three types of indexing inside format specifiers?

Question

What is the output of the following code?

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


Click to view the answer

Java, Java, Java, Javascript, and Javascript

Note

The first format specifier uses the explicit indexing to use the first argument of "Java".

The second and the fourth format specifiers (both "%s") use ordinary indexing.

The third and the fifth format specifiers (both "%<s") use relative indexing.

When you have some format specifiers that use ordinary indexing and some explicit indexing, ignore the format specifiers that use explicit indexing and number the format specifiers that use ordinary indexing as 1, 2, and so on.

Using this rule, you can think of the above statement the same as the following one:

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

Demo

public class Main {
  public static void main(String[] args) {

    System.out.printf("%1$s, %s, %<s, %s, and %<s", "Java", "Javascript");
  }// w  ww. jav a2 s. c om

}

Result