Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the $ in Java's format strings

Tags:

java

formatter

 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 $?

like image 955
andandandand Avatar asked Dec 16 '09 14:12

andandandand


People also ask

How do you use %s in string format?

%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) .

What is %d and %s in Java?

%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"

What is %s and %N in Java?

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.

How do you use %s in Java?

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....


1 Answers

The 2 has nothing to do with the $:

  • %     =   Start of format string
  • 4$   =   Fourth argument ('d')
  • 2     =   width of two (right-aligned)
  • s     =   type of String
like image 117
Sven Lilienthal Avatar answered Oct 21 '22 11:10

Sven Lilienthal