Argument Index in Java


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
", "one", "two", "three", "four", "five", "six" );       System.out.printf("After reordering = %6$s %5$s %4$s %3$s %2$s %1$s
","one", "two", "three", "four", "five", "six" );       System.out.printf("Before reordering = %d %d %d
", 100, 200, 300);       System.out.printf("After reordering = %2$d %3$d %1$d
", 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
", 100, 200, 300);

But, we changed the order and displayed it as −

System.out.printf("After reordering = %2$d %3$d %1$d
", 100, 200, 300);

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 27-Jun-2020

384 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements