StringBuilder sb = new StringBuilder(); // Send all output to the Appendable object sb Formatter formatter = new Formatter(sb, Locale.US); // Explicit argument indices may be used to re-order output. formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d") // -> " d c b a"
In this case, why is a 2 appended to $?
%s in the format string is replaced with the content of language . %s is a format specifier. Similarly, %x is replaced with the hexadecimal value of number in String. format("Number: %x", number) .
%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"
They are format specifiers used in some methods like printf() to format the string. The %s is replaced with the times value (below in the example). The %n tells the console print it in a new line.
In your example, it is a placeholder character. It means when % is encountered, the next character determines how to interpret the argument and insert it into the printed result. %s means interpret as string, %d is for digit, %x is digit in hexadecimal, %f is for float, etc....
The 2
has nothing to do with the $
:
%
= Start of format string4$
= Fourth argument ('d')2
= width of two (right-aligned)s
= type of StringIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With