0Pricing
Java Academy · Lesson

Text Blocks and String.format

Write multi-line strings with text blocks and format data with String.format patterns.

Text Blocks and String.format is a free Java Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Text Blocks and String.format

Text blocks (Java 15+) allow multi-line string literals without escaping. Combined with String.format and formatted(), they make complex string output clean and readable.

What are Text Blocks?

A text block is a string literal enclosed in triple double quotes """. It preserves newlines and indentation automatically, eliminating escape sequences for multi-line content.

// Traditional multi-line string
String old = "SELECT id, name, email\n" +
             "FROM users\n" +
             "WHERE active = true\n" +
             "ORDER BY name;";

// Text block (Java 15+) — much cleaner
String sql = """
    SELECT id, name, email
    FROM users
    WHERE active = true
    ORDER BY name;
    """;

System.out.println(sql);

Indentation Handling

Text blocks automatically strip common leading whitespace. The closing """ position controls indentation.

// Leading spaces up to the closing """ are stripped
String json = """
        {
            "name": "Alice",
            "role": "admin"
        }
        """;
// Output has no leading spaces (stripped by common indent)
System.out.println(json);
// {
//     "name": "Alice",
//     "role": "admin"
// }

Embedded Quotes

Text blocks can contain double quotes without escaping (as long as three consecutive quotes do not appear). Single " and "" are fine.

String html = """
    <div class="container">
        <p class="title">Hello, World!</p>
        <a href="https://example.com">Click here</a>
    </div>
    """;
System.out.println(html);
// Note: no need to escape " inside the block

Text Blocks for JSON Templates

Text blocks shine for JSON, HTML, XML, and SQL templates used in tests or configuration.

String request = """
    {
        "email": "alice@example.com",
        "password": "secret123",
        "plan": "PRO"
    }
    """;

// In tests: compare expected JSON
String expected = """
    {
      "status": "created",
      "id": 42
    }
    """;
// Perfect for MockMvc test assertions
System.out.println(request);

formatted() with Text Blocks

Combine text blocks with formatted() (Java 15+) to create parameterized templates.

String name = "Alice";
long orderId = 1234L;
double total = 149.99;

String email = """
    Dear %s,

    Your order #%d has been confirmed.
    Total charged: $%.2f

    Thank you for shopping with us!
    """.formatted(name, orderId, total);

System.out.println(email);
// Dear Alice,
// Your order #1234 has been confirmed.
// Total charged: $149.99

Escape Sequences in Text Blocks

Text blocks support \n, \t, and Java 14+'s \ (line continuation) and \s (preserve trailing whitespace).

// \s forces a space (preserves trailing whitespace on line)
String padded = """
    line one  \s
    line two   \s
    """;

// \ (backslash at end of line) joins lines in source but keeps them as one
String poem = """
    Roses are red, \
    violets are blue.
    """;
System.out.println(poem); // Roses are red, violets are blue.

String.format Reference

Key format specifiers for String.format:

  • %s — String
  • %d — integer
  • %f — floating-point
  • %.2f — 2 decimal places
  • %n — platform newline
  • %x — hex
  • %10d — right-align in 10 chars
System.out.printf("%s | %d | %.2f | %X%n", "Item", 42, 9.99, 255);
// Item | 42 | 9.99 | FF

String formatted = String.format("%-20s %6.2f%n", "Mechanical Keyboard", 129.95);
System.out.print(formatted);
// Mechanical Keyboard 129.95

// Named format with text block
System.out.printf("""
    Order: %s
    Total: $%.2f
    Status: %s%n""", "ORD-001", 99.99, "SHIPPED");

Text Block stripIndent and translateEscapes

Two String methods work with text blocks: stripIndent() removes common leading whitespace, and translateEscapes() processes escape sequences in a runtime string.

String raw = "  hello\\n  world";
System.out.println(raw);                    // hello\n  world
System.out.println(raw.translateEscapes()); // hello (newline) world

// stripIndent removes common leading whitespace
String indented = "    line 1\n    line 2\n    line 3";
System.out.println(indented.stripIndent()); // line 1\nline 2\nline 3

Practical: HTML Email Template

Building a parameterized HTML email template with a text block.

static String buildWelcomeEmail(String name, String activationLink) {
    return """
        <!DOCTYPE html>
        <html>
          <body>
            <h1>Welcome, %s!</h1>
            <p>Click the link below to activate your account:</p>
            <a href="%s">Activate Account</a>
          </body>
        </html>
        """.formatted(name, activationLink);
}

System.out.println(buildWelcomeEmail("Alice",
    "https://app.example.com/activate?token=abc123"));

Text Blocks vs String.join

For lists of items, String.join or Collectors.joining is more flexible than a text block. Use text blocks for fixed multi-line content; join for dynamic lists.

import java.util.*;
import java.util.stream.*;

List<String> features = List.of("Unlimited storage", "Priority support", "AI assistant");

// Dynamic list: join
String bullet = features.stream()
    .map(f -> "  • " + f)
    .collect(Collectors.joining("\n"));
System.out.println(bullet);
// • Unlimited storage
// • Priority support
// • AI assistant

// Fixed template: text block + formatted
String plan = """
    PRO Plan — $29/month
    Features:
    %s
    """.formatted(bullet);
System.out.println(plan);

Quick Check

What does the closing """ position control in a text block?

Recap: Text Blocks and String.format

Key takeaways:

  • Text blocks (Java 15+) use triple quotes and preserve multiline structure without escaping
  • Common leading whitespace is stripped automatically based on closing \"\"\" position
  • Double quotes inside text blocks need no escaping
  • Use .formatted() on a text block for parameterized templates
  • String.format specifiers: %s, %d, %.2f, %n, %x, width/alignment flags
  • Use \s at line end to preserve trailing spaces; \ at line end to join lines

Frequently asked questions

Is the “Text Blocks and String.format” lesson free?

Yes — the full text of “Text Blocks and String.format” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Text Blocks and String.format”?

Write multi-line strings with text blocks and format data with String.format patterns. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Text Blocks and String.format” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. String Immutability and the String Pool
  2. StringBuilder for Efficient Concatenation
  3. Text Blocks and String.format
  4. Regular Expressions with Pattern and Matcher
← Back to Java Academy