Understanding the $ in Java's format strings

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

The 2$ means put the second argument from the list here. The $ follows a number not precedes it. Similarly, 4$ means put the forth argument here.

To clarify, we can break down the %2$2s format into its parts:

  • % - indicates this is a format string

  • 2$ - shows the second value argument should be put here

  • 2 - the format is two characters long

  • s - format the value as a String

You can find more information in the documentation.