Home/Learn/Java A–Z/String Formatting

String Formatting

Beginner
Modern Java

Java provides multiple ways to format strings — String.format, printf, the new formatted() method, and StringBuilder — each with distinct use cases.

Overview

String formatting in Java spans several APIs: String.format() for printf-style formatting, System.out.printf() for direct console output, the instance method String::formatted (Java 15+), MessageFormat for locale-aware patterns, and StringBuilder for manual concatenation. Understanding format specifiers, performance implications, and when to use each API is essential for writing clear, efficient Java code.

String.format and Format Specifiers

String.format() uses printf-style format specifiers. Key specifiers: %s (string), %d (decimal integer), %f (floating point), %n (platform newline), %b (boolean), %c (char), %x (hex).

Width and precision: %10s (right-align in 10 chars), %-10s (left-align), %.2f (2 decimal places), %08d (zero-pad to 8 digits).

StringFormat.java
String name = "Alice";
int age = 30;
double gpa = 3.756;

// Basic formatting
String s = String.format("Name: %s, Age: %d, GPA: %.2f", name, age, gpa);
// "Name: Alice, Age: 30, GPA: 3.76"

// Width and alignment
System.out.printf("%-15s %5d %8.2f%n", name, age, gpa);
// "Alice              30     3.76"

// Zero-padding, hex
System.out.printf("ID: %08d  Hex: %X%n", 42, 255);
// "ID: 00000042  Hex: FF"

// Java 15+ — instance method on String
String result = "Hello, %s! You are %d years old.".formatted(name, age);

StringBuilder for Efficient Concatenation

String concatenation with + in a loop creates many temporary objects because String is immutable. StringBuilder is the mutable counterpart — it pre-allocates a buffer and appends without creating intermediates.

In Java 9+, the JVM uses invokedynamic-based string concatenation (StringConcatFactory) for + at compile time, which is often as fast as StringBuilder for simple cases. But for loops, explicit StringBuilder is still best practice.

StringBuilder.java
// Avoid: O(n²) allocations in a loop
String result = "";
for (int i = 0; i < 1000; i++) {
    result += i + ",";  // new String each iteration
}

// Prefer: StringBuilder
StringBuilder sb = new StringBuilder(4096);
for (int i = 0; i < 1000; i++) {
    sb.append(i).append(',');
}
String result = sb.toString();

// Useful StringBuilder methods
sb.insert(0, "START:");
sb.delete(3, 6);
sb.reverse();
sb.replace(0, 5, "NEW");
int len = sb.length();

String.join and Collectors.joining

String.join() and Collectors.joining() provide clean, null-safe ways to join collections or arrays with a delimiter, prefix, and suffix.

Prefer these over manual StringBuilder loops for joining use cases. They are readable and often more performant.

StringJoin.java
import java.util.List;
import java.util.stream.Collectors;

List<String> names = List.of("Alice", "Bob", "Charlie");

// String.join
String csv = String.join(", ", names);
// "Alice, Bob, Charlie"

// Collectors.joining with prefix/suffix
String bracketed = names.stream()
    .collect(Collectors.joining(", ", "[", "]"));
// "[Alice, Bob, Charlie]"

// Join with transformation
String upper = names.stream()
    .map(String::toUpperCase)
    .collect(Collectors.joining(" | "));
// "ALICE | BOB | CHARLIE"

Key Points to Remember

  • %s, %d, %f, %n are the most common format specifiers in String.format / printf.
  • String::formatted (Java 15+) is the instance-method equivalent of String.format.
  • Use StringBuilder in loops to avoid O(n²) string allocations.
  • String.join and Collectors.joining are the clean way to join collections.
  • String concatenation with + is optimised by the compiler for simple expressions but not loops.

Practice String Formatting in the Playground

Run and modify code directly in your browser - no setup needed.

Interview Questions

Sign in to ask Aria
1

What is the time complexity difference between + concatenation in a loop vs. StringBuilder?

EasyAmazon
2

What does the format specifier %-10.2f mean?

MediumTCS
3

When should you use StringBuffer instead of StringBuilder?

EasyInfosys
4

How does Java 9+ improve string concatenation with +?

HardOracle
5

What is the difference between String.join and Collectors.joining?

EasyGoogle

Ask Aria about String Formatting

Your personal AI tutor — ask anything about this concept