Amerpsand format flag in java

I have existing java code that is used to format a string. This code fails for the below format - java.util.FormatFlagsConversionMismatchException:..Based on other SO issues, I see its more related to Java version thats used.

Question..

  1. What does the '%1$#' format does..Mostly Im not able to find the '$' & '#' format rules while I googled.

  2. How to fix this issue?

Java code

String test = String.format("%1$#" + 2 + "s", 01);
Jon Skeet
people
quotationmark

From the docs of java.util.Formatter:

The format specifiers for general, character, and numeric types have the following syntax:

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

So %1$#2s means an argument_index of 1, a flags value of # ("The result should use a conversion-dependent alternate form"), a width of 2, and a conversion of s (string).

For %s conversions, the alternate form is used by passing it to Formattable:

If the argument is null, then the result is "null". If the argument implements Formattable, then its formatTo method is invoked. Otherwise, the result is obtained by invoking the argument's toString() method.

If the '#' flag is given and the argument is not a Formattable , then a FormatFlagsConversionMismatchException will be thrown.

I suspect you don't really want # in this case.

people

See more on this question at Stackoverflow