BackendBench
Coffee
Free tool

Java String.format tester

Type a format string and arguments and see what String.format prints, or which exception it throws, without compiling anything.

Result

Testing String.format without compiling

String.format, printf and formatted() all use java.util.Formatter. Its mini-language is compact and a little unforgiving: one wrong letter, a missing argument or a type mismatch throws a runtime exception, usually inside a log statement or an error message at the worst time. This tester lets you try a format string against sample arguments and see exactly what Java would print, or which exception it would throw.

Put the format string in the first box and one argument per line in the second. Numbers without a decimal point are Integers (add an L for Long), numbers with a point are Doubles, true and false are Booleans, null is null, and anything else is a String. The type matters: %x on the Integer -1 prints ffffffff, but on a Long it prints sixteen f's.

The parts of a specifier

A specifier is %[argument_index$][flags][width][.precision]conversion. The argument index lets you reuse or reorder arguments (%2$s %1$s), and %<s repeats the previous one. Flags include - (left-justify), 0 (zero pad), + (always show sign), a space, , (grouping separators) and ( (negative numbers in parentheses). Precision means digits after the point for floats, but the maximum length for strings.

How faithful is the model?

It implements the common conversions (s, d, f, e, g, x, o, b, c, h, n and %) and reports Java's exception names. Locale-specific output and the date/time conversions (%t) are not modelled, and grouping uses commas as in the US locale. Confirm anything unusual on your JDK. Nothing is sent to a server.

Frequently asked questions

What is the difference between %d, %s and %f?

%d formats whole numbers (int, long, BigInteger), %f formats floating point numbers (double, float, BigDecimal), and %s calls toString() on anything. Passing a double to %d throws IllegalFormatConversionException.

How do I pad with zeros or spaces?

Use a width, with the 0 flag for zeros: %05d gives 00042 and %5d gives " 42". The minus flag left-justifies: %-5d gives "42 ". The 0 flag needs a width or you get MissingFormatWidthException.

Why does %.2f round 0.125 to 0.13?

The Formatter documentation says values are rounded using the round half up algorithm, so 0.125 becomes 0.13, where some languages, such as Python, round half to even and give 0.12.

How do I print a literal percent sign or a newline?

Write %% for a percent sign and %n for the platform line separator. A single % followed by something that is not a conversion throws UnknownFormatConversionException.

More tools you might need