tags:

views:

117

answers:

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

+3  A: 

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.

Dave Webb
Why downvoted? It's a correct answer.
Joey
Tactical downvoting?
Dave Webb
Well, now you have a tactical upvote, then :-)
Joey
So, you’re a vote faker, Johannes? :)
Bombe
It was actually downvoted, when it was a wrong answer. As it is correct now, downvote removed.
Sven Lilienthal
@Sven - The answer never changed, I think you must have read it wrong. I've added to but not changed any content.
Dave Webb
Well, when I downvoted it read: "The 2$ means put the second argument from the list here." That's not what I would count as a correct answer.
Sven Lilienthal
It still says exactly that now and you've said its now correct.
Dave Webb
On itself, it's wrong or at least not answering the question, but put into context, it's right.
Sven Lilienthal
+4  A: 

The 2 has nothing to do with the $:

  • % = Start of format string
  • 4$ = Fourth argrument ('d')
  • 2 = width of two
  • s = String
Sven Lilienthal
+1  A: 

Those are positional arguments where %4$2s signals to format the fourth argument as a string with width 2. This is especially helpful when providing strings for localization where arguments need to be reordered without touching the source code.

The format specifiers for types which are used to represents dates and times have the following syntax:

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

The optional argument_index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc. —Formatter documentation

Joey
Still, I like .NET's format strings better as they make the position of arguments much clearer.
Joey