1

In my production code I noticed that the method java.lang.String#format "eats" the first character of the String to be formatted when used without specifying the formatting parameters.

Thus

String.format("%%myStringValue\r\n");

produces the following console output: %myStringValue

See, how one of the percent characters gets away? Why is it so? I couldn't find any hints on that in the docblock of the method.

Arthur Eirich
  • 3,368
  • 9
  • 31
  • 63
  • 3
    As described in [the documentation](https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html) under "Conversions", `%%` is converted to `%`. – khelwood Nov 23 '17 at 10:51
  • It works as it is supposed to work. Since `%` is a special character in a format string, you need to escape it with `%%` to get a single percent sign in the output. – Jesper Nov 23 '17 at 10:51
  • Possible duplicate of [How to escape % in String.Format?](https://stackoverflow.com/questions/5011932/how-to-escape-in-string-format) – Rob Obdeijn Nov 23 '17 at 10:52
  • Yes, that is the correct behaviour when using the escape character. – jorjSB Nov 23 '17 at 10:56
  • Oh my god... My apologies, I had a "blackout". I used this thing so many times while specifying exception messages. for example. The double `%` chars confused me a bit. Thank you all for the quick responses. – Arthur Eirich Nov 23 '17 at 11:04

1 Answers1

2

The sequence %% is an 'escape sequence' to be able to print the % char itself, which otherwise would be interpreted as format specifier

gtosto
  • 1,381
  • 1
  • 14
  • 18