Understanding the $ in Java's format strings

andandandand picture andandandand · Dec 16, 2009 · Viewed 45.8k times · Source
 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 $?

Answer

Sven Lilienthal picture Sven Lilienthal · Dec 16, 2009

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