Scrivio Interview library
ConceptIntermediate6 min read · updated 12 November 2026

Compare String.format, String.formatted, MessageFormat, DecimalFormat and plain concatenation for building strings in a service. Which are thread-safe and which are costly?

Plain concatenation is the cheapest for simple cases, since JDK 9 compiles it through invokedynamic. String.format and formatted() are thread-safe because each call creates its own Formatter, but they parse the pattern on every call, so they are fine for occasional use and costly in hot loops. MessageFormat adds positional arguments and choice formats, with single-quote escaping that surprises people, and DecimalFormat, like SimpleDateFormat, is not thread-safe, so instances must be confined to one thread or created per use; for dates, the immutable, thread-safe DateTimeFormatter should replace SimpleDateFormat.

Why this question is asked

Every service builds strings for messages, logs, file names and reports, and Java has several ways to do it, each with different costs and traps. Picking the wrong one causes either slow hot paths or rare, hard-to-reproduce corruption when a formatter is shared between threads. Interviewers ask this comparison to see whether we know which tools are safe to share and which are expensive. In this answer, we will go through each option with an example, look at the thread-safety problem of DecimalFormat and SimpleDateFormat, compare the costs, and end with what to use where.

1A Quick Recap of the Options

Concatenation with + joins values directly. String.format(pattern, args) and its instance form pattern.formatted(args) use java.util.Formatter with printf-style specifiers such as %s, %d and %.2f. MessageFormat, in java.text, uses numbered placeholders such as {0} and {1} and is designed for translated messages, where word order changes between languages. DecimalFormat, also in java.text, formats numbers with a pattern such as #,##0.00.

These classes were written at different times with different goals, which is why they disagree on thread safety and cost.

Formatting options compared
OptionThread-safeCost per callWatch out for
+ concatenationyes (no shared state)lowestno formatting control
String.format / formatted()yes (new Formatter per call)high: parses patterndefault locale
MessageFormat instancenomedium if reusedquote escaping, number grouping
DecimalFormat instancenolow if reusedsharing across threads
SimpleDateFormat instancenolow if reusedsharing across threads
DateTimeFormatteryes (immutable)lowpattern letters differ slightly

2String.format and formatted(): Safe but Costly

String.format creates a new Formatter on each call, parses the pattern to find each specifier, allocates the varargs array and formats each argument with the locale's rules. Because nothing is shared, it is safe from any thread. But the parsing is repeated on every call, which makes it several times slower than concatenation for the same output.

Java
String a = String.format("order %d for %s", 42, "ann"); // order 42 for ann
String b = "order %d for %s".formatted(42, "ann"); // same, Java 15+
String c = "order " + 42 + " for " + "ann"; // same text, much cheaper
String d = String.format(Locale.ROOT, "%08.2f", 3.14159); // 00003.14: width and precision are where format shines

So String.format is the right tool when we need its features, widths, padding, precision and locale-aware numbers, in code that does not run millions of times a second. In a hot loop or a disabled log statement, concatenation or parameterized logging is better.

3MessageFormat: Positional Arguments and Its Quotes

MessageFormat's strength is positional arguments, so a translator can move {1} before {0}, and choice formats, which pick text by number, such as 'no files', 'one file' or '{0} files'. Two behaviours regularly surprise people. A single quote starts a quoted section, so an apostrophe in a message swallows the placeholders after it, and numbers are formatted with the locale's grouping, so an id of 1234 becomes 1,234.

Java
System.out.println(MessageFormat.format("It's {0}", "ready")); // Its {0}: the quote ate the placeholder
System.out.println(MessageFormat.format("It''s {0}", "ready")); // It's ready: '' is a literal quote
System.out.println(MessageFormat.format("Order {0}", 1234)); // Order 1,234 (in an en locale)
System.out.println(MessageFormat.format("Order {0,number,#}", 1234)); // Order 1234
System.out.println(MessageFormat.format("{0,choice,0#no files|1#one file|1<{0} files}", 3)); // 3 files

The static MessageFormat.format creates a new instance each time, which is safe but repeats the pattern parsing. A MessageFormat instance can be reused to save that cost, but instances are not thread-safe, so a shared one needs the same care as DecimalFormat.

4DecimalFormat and SimpleDateFormat: Not Thread-Safe

DecimalFormat and SimpleDateFormat keep working state in fields while they format or parse: the digit list being built, a Calendar holding the date being processed. If two threads use the same instance at once, they overwrite each other's state. The result is not an exception but wrong output: a date from another request, a mangled number, or occasionally an ArrayIndexOutOfBoundsException deep inside the class.

Java
// Broken: one instance shared by every request thread
private static final SimpleDateFormat DATE = new SimpleDateFormat("yyyy-MM-dd");
String day = DATE.format(order.getCreated()); // rare wrong dates under load
// Fix for dates: DateTimeFormatter is immutable and thread-safe
private static final DateTimeFormatter DAY = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String day2 = DAY.format(order.getCreatedAt()); // LocalDate or similar: safe from any thread
// Fix for numbers: confine an instance to each thread, or create one per call
private static final ThreadLocal<DecimalFormat> MONEY =
ThreadLocal.withInitial(() -> new DecimalFormat("#,##0.00", DecimalFormatSymbols.getInstance(Locale.ROOT)));
String amount = MONEY.get().format(1234.5); // 1,234.50
Step throughTwo threads sharing one SimpleDateFormat
Thread AShared formatterThread B
format(2026-01-05): sets internal calendar
format(2026-11-30): overwrites the calendar
A's call continues with B's fields
returns 2026-11-30 for A's date
returns 2026-11-30

5 messages in order. Play them, or step through them one at a time.

No exception, just wrong output, which is why this bug survives testing.

The bug is dangerous because it passes every single-threaded test and appears only under concurrent load. DateTimeFormatter from java.time solves it for dates by being immutable. For numbers, there is no immutable java.text equivalent, so we confine instances, with a ThreadLocal or by creating one per call, which costs more allocation but is simple. On virtual threads, prefer creating per call or a small helper, since a ThreadLocal per virtual thread gives little reuse.

5What to Use Where

For simple messages, keys, file names and exceptions, plain concatenation is fastest and clearest, and invokedynamic makes it efficient. For logging, parameterized messages are better still, because they skip formatting when the level is off. For output that needs widths, precision or a specific locale, String.format with an explicit Locale is the right tool, outside hot loops.

For translated user-facing messages, MessageFormat, usually through a ResourceBundle or Spring's MessageSource, handles positional arguments and plurals; we just remember to double the quotes. For dates and times, DateTimeFormatter, always. And DecimalFormat only for patterns that the others cannot express, with instances confined to a thread or created per call, never shared as a static field.

6Follow-up questions

Is a static final DecimalFormat safe if we only call format()?

No. format() also mutates internal state, such as the digit buffer, so concurrent calls can corrupt each other's results. Only immutable formatters such as DateTimeFormatter are safe to share as constants.

Why not synchronize on the shared SimpleDateFormat?

It works, but it turns formatting into a point of contention for every request thread. Moving to DateTimeFormatter removes the problem and the lock, and for numbers a per-call or per-thread instance avoids it without serialising threads.

Does Spring help with any of this?

Spring's MessageSource handles MessageFormat-style messages per locale and caches the parsed formats safely, and Spring's formatting annotations such as @DateTimeFormat and @NumberFormat use thread-safe formatters internally. In our own code, we still need to avoid shared java.text formatters.

7Conclusion

In this answer, we compared the options: concatenation is the cheapest and fine for simple text; String.format and formatted() are thread-safe but parse their pattern on every call and use the default locale; MessageFormat offers positional arguments and choice formats but treats single quotes specially and groups numbers; and DecimalFormat and SimpleDateFormat are not thread-safe, so they must be confined or created per call, with DateTimeFormatter replacing SimpleDateFormat entirely. Choosing the tool by the job, and never sharing a mutable formatter, avoids both slow hot paths and silent corruption.

What to say in the interviewAbout 90 seconds aloud

Open with

I would split them by cost and by thread safety. Plain concatenation is the cheapest, and since JDK 9 it compiles to invokedynamic, which computes the exact size, so for simple messages and keys I just use plus.

Then, if they want more

String.format and formatted are thread-safe because every call creates its own Formatter, but they parse the pattern each time and use the default locale, so I use them with an explicit locale when I need widths or precision, and keep them out of hot loops and disabled log statements.

MessageFormat is for translated messages: positional arguments and choice formats for plurals. Its traps are that a single quote starts a quoted section, so It's swallows the placeholder unless you write two quotes, and numbers get grouping, so an id of 1234 prints as 1,234 unless you use a number pattern.

Then the thread-safety problem: MessageFormat, DecimalFormat and SimpleDateFormat instances keep mutable state while formatting, so sharing one as a static field gives silently wrong output under load, not an exception. For dates I replace SimpleDateFormat with DateTimeFormatter, which is immutable and safe as a constant. For numbers I create a DecimalFormat per call or confine it per thread.

So my default is concatenation or parameterized logging, String.format with a locale for formatted output, MessageSource for user messages, and java.time for dates.

About this answer

Last updated
12 November 2026
Versions it names
Java 15, Java 9
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Compare String.format, String.formatted, MessageFormat, DecimalFormat and plain...": https://scrivio-interview-library.netlify.app/java/strings/41c609994e/