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

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);

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