Phase 8 of 20 · Topic 8.5

Text Blocks (Java 15+) & Formatted Multiline Strings

1Concept

Java 15 introduced Text Blocks (`"""`). Text blocks preserve whitespace formatting, eliminate messy escape quotes (`\"`), automatically calculate and strip common indentation, and support built-in formatting with `.formatted()`.

2Architecture Diagram

Source Code:
String json = """
    {
      "service": "Auth",
      "status": 200
    }
    """; ---> Common 4-space indentation automatically stripped!

3Code Example

Core Java
public class TextBlocksDemo {
    public static void main(String[] args) {
        String serviceName = "PaymentGateway";
        int port = 8443;

        String jsonConfig = """
            {
              "service": "%s",
              "port": %d,
              "ssl": true
            }
            """.formatted(serviceName, port);

        System.out.println("Formatted JSON Configuration:");
        System.out.println(jsonConfig);
    }
}

4Expected Output

Formatted JSON Configuration:
{
  "service": "PaymentGateway",
  "port": 8443,
  "ssl": true
}

5Key Takeaways

  • Opening `"""` must be followed immediately by a newline.
  • Text blocks automatically strip incidental leading whitespace based on the leftmost character.
  • Use `\` at the end of a line in a text block to suppress the newline character.