Memra

String.format / printf & escape sequences

◈ 6 cards

Format specifiers, padding and precision, escape sequences, and printf vs format.

Formatted output

Java borrows C-style format strings. System.out.printf(fmt, args...) prints a formatted line; String.format(fmt, args...) returns the formatted text as a String (handy for building a log line). Both take a format string containing format specifiers that each consume one argument.

A specifier has the shape %[flags][width][.precision]conversion:

  • %d — decimal integer
  • %f — floating-point (default 6 decimals)
  • %s — string (calls the argument's toString)
  • %c — character
  • %b — boolean
  • %x — hexadecimal
  • %n — platform-independent newline (prefer it over \n in format strings)
  • %% — a literal percent sign

Worked example. Format a log line with a fixed-width label and two decimals.

String line = String.format("[%-8s] temp=%6.2f%n", "SENSOR", 21.5);
// [SENSOR  ] temp= 21.50\n

Reading that format string left to right: - %-8s — the string "SENSOR" in a field 8 wide, - means left-justified, so it is padded on the right to "SENSOR ". - temp= — literal text, printed as-is. - %6.2f — the double 21.5 in a field 6 wide with 2 decimals: " 21.50" (a leading space pads to width 6). - %n — a newline.

Escape sequences

Inside a string literal, a backslash introduces an escape sequence: \n newline, \t tab, \" a literal double-quote, \\ a literal backslash, \' a single quote, \r carriage return. To put a Windows path in a string you must double every backslash: "C:\\temp\\out.txt".

%-8sSENSOR··"SENSOR"pad%8s··SENSORpad"SENSOR"· is a padding space. 8 is the field width.
Width is a <em>minimum</em> field size, never a maximum — a longer argument is printed in full rather than truncated. All the <code>-</code> flag decides is which side the padding lands on, which is why <code>%6.2f</code> (no flag) right-justifies <code>21.50</code> into <code>" 21.50"</code> and the numbers in a column line up.
NORMAL ~/memra/learn/comp-308/format-printf-escapes utf-8 LF