Java - Format Specifier Ordinary Index

Introduction

When a format specifier does not set an argument-index value, it is called ordinary indexing.

In ordinary indexing, the argument-index is determined by the position of the format specifier in the format string.

The first format specifier without argument-index has the index of 1, the second has the index of 2, and so on.

The format specifier with the index 1 refers to the first argument; the format specifier with the index 2 refers to the second argument; and so on.

Example

The following code shows the indices of the format specifiers and the arguments.

Indices of format specifiers   Indices of Arguments
1     2         3              1           2            3
%s,   %s, and   %s             "Java"      "Json"       "Javascript"

If the number of arguments is more than the number of format specifiers in the format string, the extra arguments are ignored.

The fourth argument, "Extra", is an extra argument in the following code, which is ignored.

System.out.printf("%s, %s, and %s", "Java", "Json", "Javascript", "extra");

Output:

Java, Json, and Javascript

A java.util.MissingFormatArgumentException is thrown if a format specifier references a non-existent argument.

The following code will throw the exception because the number of arguments is one less than the number of format specifiers.

There are three format specifiers, but only two arguments.

//throws a runtime exception
System.out.printf("%s, %s, and %s", "Java", "Json");

Note

The last argument to the format() method of the Formatter class is a varargs argument. You can pass an array to a varargs argument.

The following code is valid even though it uses three format specifiers and only one argument of array type.

The array type argument contains three values for the three format specifiers.

String[] names = {"Java", "Javascript", "Json"};
System.out.printf("%s, %s, and %s", names);
Java, Javascript, and Json

The following code is valid because it passes four values in the array type argument but has only three format specifiers:

String[] names = {"Java", "Javascript", "Json", "Extra"};
System.out.printf("%s, %s, and %s", names);

The following code is not valid because it uses an array type argument that has only two elements and there are three format specifiers.

A MissingFormatArgumentException will be thrown when the following snippet of code is run.

Demo

public class Main {
  public static void main(String[] args) {
    String[] names = { "Java", "Javascript" };
    System.out.printf("%s, %s, and %s", names); // Throws an exception
  }//  w  w w .ja  v a  2  s  . c o  m
}