Argument Index in Java

Java 8Object Oriented ProgrammingProgramming

Argument indices allow programmers to reorder the output. Let us see an example.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      System.out.printf("Before reordering = %s %s %s %s %s %s\n", "one", "two", "three", "four", "five", "six" );
      System.out.printf("After reordering = %6$s %5$s %4$s %3$s %2$s %1$s\n","one", "two", "three", "four", "five", "six" );
      System.out.printf("Before reordering = %d %d %d\n", 100, 200, 300);
      System.out.printf("After reordering = %2$d %3$d %1$d\n", 100, 200, 300);
   }
}

Output

Before reordering = one two three four five six
After reordering = six five four three two one
Before reordering = 100 200 300
After reordering = 200 300 100

Above, we have reordered the output completely. Before ordering, we displayed normally.

System.out.printf("Before reordering = %d %d %d\n", 100, 200, 300);

But, we changed the order and displayed it as −

System.out.printf("After reordering = %2$d %3$d %1$d\n", 100, 200, 300);
raja
Published on 14-Dec-2018 11:04:31
Advertisements