Course contentsShow
← Java
Lesson 2243 of 2,87043. String Handling in DepthFree lesson

Text Blocks vs String Concatenation

Compare text blocks to traditional string concatenation and StringBuilder for readability, maintainability, and use cases.

Text Blocks vs String Concatenation

What you'll learn: How text blocks compare to traditional string concatenation and StringBuilder for readability, maintainability, and choosing the right tool for your needs.

The Core Comparison

When building multi-line strings, you have three main approaches: concatenation with +, StringBuilder, and text blocks. Each has distinct strengths:

String concatenation (+ operator) is simple for short strings but quickly becomes messy with multi-line content. Each + creates intermediate String objects, and manually managing line breaks (\n) and escaping quotes clutters your code.

StringBuilder solves the performance problem by building strings efficiently without intermediate objects. However, you still manually append line breaks and escape characters, making the code harder to read when representing structured text like JSON, SQL, or HTML.

Text blocks shine for readability and maintainability when working with multi-line formatted text. They eliminate escaping nightmares, preserve indentation naturally, and let you see the actual structure of your output directly in the source code.

When to Use What

  • Short, single-line strings: Use simple concatenation or formatted()
  • Dynamic string building in loops: Use StringBuilder
  • Multi-line literals (SQL, JSON, HTML, templates): Use text blocks
  • Performance-critical repeated concatenation: Use StringBuilder

Example Contrast

With concatenation, JSON becomes:

String json = "{\n" + "  \"name\": \"Alice\",\n" + "  \"age\": 30\n" + "}";

With text blocks, it's naturally readable:

String json = """
    {
      "name": "Alice",
      "age": 30
    }
    """;

Key Takeaway: Use text blocks for multi-line literals where readability matters; use StringBuilder for dynamic construction; use concatenation for simple cases. Text blocks excel at maintainability, not performance.