Java String Formatting and Templates
String formatting techniques: printf, format, MessageFormat, StringJoiner, and text block interpolation.
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
public class StringFormatting {
public static void main(String[] args) {
// 1. String.format / printf
String name = "Alice";
int age = 30;
double balance = 1234.567;
String formatted = String.format("Name: %-10s Age: %03d Balance: $%,.2f", name, age, balance);
System.out.println(formatted);
// Name: Alice Age: 030 Balance: $1,234.57
// 2. Date/time formatting
System.out.printf("Now: %tF %tT%n", LocalDateTime.now(), LocalDateTime.now());
// 3. MessageFormat (i18n-friendly)
String msg = MessageFormat.format(
"Hello {0}, you have {1,number,integer} messages",
"Bob", 42);
System.out.println(msg);
// 4. StringJoiner
StringJoiner joiner = new StringJoiner(", ", "[", "]");
joiner.add("apple").add("banana").add("cherry");
System.out.println(joiner); // [apple, banana, cherry]
// 5. Collectors.joining
List<String> fruits = List.of("apple", "banana", "cherry");
String joined = fruits.stream().collect(Collectors.joining(" | ", "{ ", " }"));
System.out.println(joined); // { apple | banana | cherry }
// 6. Text blocks for templates
String html = """
<html>
<body>
<h1>Hello, %s!</h1>
<p>Your balance: $%,.2f</p>
</body>
</html>
""".formatted(name, balance);
System.out.println(html);
// 7. StringBuilder for dynamic construction
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
sb.append("Row ").append(i).append(": ")
.append("*".repeat(i + 1)).append("\n");
}
System.out.print(sb);
// 8. Repeat and pad
String padded = "Hello".concat(" ".repeat(15)).substring(0, 20);
System.out.printf("[%20s]%n", "right-aligned");
System.out.printf("[%-20s]%n", "left-aligned");
}
}Use Cases
- Formatted log messages and reports
- HTML/SQL template generation
- Internationalized string formatting
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Reverse a String in Java
Multiple ways to reverse a string in Java including StringBuilder, char array, and stream approaches.
Best for: String manipulation in coding interviews
Java Date/Time API — Modern Operations
Work with LocalDate, LocalDateTime, ZonedDateTime, Duration, Period, and date formatting.
Best for: Date arithmetic and business day calculations
String Pool and Interning
Understand Java string pooling: intern(), identity vs equality, memory optimization, and common pitfalls.
Best for: Memory optimization for repeated string values
String Templates and Multiline Strings
Format strings in Kotlin: templates, raw strings, trimMargin, trimIndent, and template processing.
Best for: Dynamic string construction and formatting