Home > other >  What does "%1$d" mean in a format string?
What does "%1$d" mean in a format string?

Time:02-18

I can't figure out what this %1$d format specifier means. Can someone help me?

int zahl = 100;
System.out.format("A number: %1$d %n", zahl);

CodePudding user response:

1$ represents your first argument which is your zahl variable. %d is the format specifier for integer. The $ convention is used to avoid multiple times your argument is being reused. One example is,

Date date = new Date();
System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);

In the above print statement instead of passing your date variable multiple number of times, you can achieve it instead in the following way,

System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n", date);

CodePudding user response:

From the docs linked in the comment, the 1$ refers to the argument index while the d refers to the fact that the result is formatted as a decimal integer.

More explicitly, one relevant section of the documentation that might help you understand the syntax is:

The format specifiers for general, character, and numeric types have the following syntax:

%[argument_index$][flags][width][.precision]conversion

So the general form of "%1$d" would be %[argument_index$]conversion

CodePudding user response:

x$ means arguments number x.

The following will print Hello World:

System.out.printf("%s %s", "Hello", "World");

Both below will print World Hello:

System.out.printf("%2$s %1$s", "Hello", "World");
System.out.printf("%s %s", "World", "Hello");

From https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax:

The format specifiers for general, character, and numerical types have the following syntax: %[argument_index$][flags][width][.precision]conversion

  • Related