HuntExams Academy logo
JavaBeginner#strings

What is the difference between String.format and concatenation?

Answer

String.format uses a format string with placeholders for cleaner, locale-aware formatting of numbers, dates, and padding. Concatenation with + is simpler but creates intermediate objects and lacks formatting control.

Example

String s = String.format("%s is %d years old", "Bob", 30);
// "Bob is 30 years old"

Detailed explanation

In Java, string concatenation joins values directly, while String.format builds text from a template containing format specifiers. For example, "Bob" + " is " + 30 + " years old" and String.format("%s is %d years old", "Bob", 30) both produce "Bob is 30 years old". Concatenation is usually clearer for short messages with little formatting. String.format becomes useful when the output needs controlled precision, field width, padding, or locale-sensitive number and date representations.

String.format uses Java's Formatter machinery to interpret its template and match arguments to specifiers. Here, %s requests a string representation and %d requests a decimal integer. Other examples include %.2f for two fractional digits and %05d for an integer padded with leading zeros to a minimum width of five characters. The overload without an explicit Locale uses the default formatting locale, so output can vary across environments. For predictable decimal formatting, write String.format(Locale.US, "%.2f", 12.5), which produces "12.50". Invalid specifiers or incompatible argument types can cause an IllegalFormatException at runtime.

Concatenation does not parse a formatting template; it converts operands to text as required and joins them. However, saying that every + necessarily creates an intermediate String is misleading. The compiler can fold constant expressions such as "Hello " + "Java" into one constant. For nonconstant expressions, Java 8 compilers commonly generate StringBuilder operations, while modern Java compilers generally use invokedynamic-based concatenation, allowing the runtime to optimise construction. Both approaches ultimately produce a String, whose contents cannot be modified.

String.format generally has more overhead because it processes a template and accepts variable arguments, potentially involving an argument array and boxing of primitive values. Prefer concatenation for simple expressions and formatting when presentation requirements justify it. For repeatedly accumulating text inside a loop, use one StringBuilder rather than repeatedly assigning result = result + part. In interviews, explain readability, formatting capabilities, locale behaviour, and performance trade-offs without claiming that either approach is always better.

Key points to remember

  • Concatenation with + directly joins text and values; String.format interprets a template.
  • Format specifiers support precision, minimum field widths, padding, and formatted numbers or dates.
  • Use an explicit Locale when locale-sensitive output must be predictable.
  • String.format generally adds template-processing overhead and can fail on invalid formats at runtime.
  • Concatenation can be optimised; use StringBuilder for repeated accumulation in loops.

Common mistakes candidates make

  • Claiming that every + operation necessarily allocates an intermediate String, ignoring compiler and runtime optimisations.
  • Using incompatible arguments, such as passing "30" to %d, and expecting compile-time validation.
  • Relying on the default locale when tests or consumers require a specific decimal separator.

Likely follow-up questions

Why is StringBuilder better for concatenation inside a loop?

Repeatedly concatenating onto an existing String typically copies the growing contents into a new result each iteration. StringBuilder maintains a mutable buffer, reducing repeated copying, and produces a String when you call toString().

What happens when a format specifier does not match its argument?

String.format("%d", "30") throws IllegalFormatConversionException, a subclass of IllegalFormatException. The string argument is not automatically parsed into an integer.

How does locale affect String.format?

Locale can affect decimal separators, grouping separators, and textual date elements. For example, String.format(Locale.US, "%.2f", 12.5) produces "12.50", while Locale.GERMANY produces "12,50".

Interview tip: Start with the shared output example, show one precision or padding requirement, and then explain the performance trade-off without making absolute claims.

Related Interview Questions

1
JavaIntermediate#strings

How do you split a String and handle edge cases with delimiters that are regex special characters?

Open
2
JavaIntermediate#collections

What is the difference between Set implementations HashSet, LinkedHashSet, and TreeSet?

Open
3
JavaIntermediate#collections

What is the difference between Iterator and ListIterator?

Open