Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 02 / Topic 8 of 9

Text blocks

A text block is a string literal that spans multiple lines, written between """ on its own line and a closing """. It needs no \n for new lines and no \" to escape quotes.

String receipt = """
        Spice Garden
        123 FC Road, Pune
        GSTIN: 27AAAAA0000A1Z5
        """;

Output (examples/07_text_blocks.java):

Spice Garden
123 FC Road, Pune
GSTIN: 27AAAAA0000A1Z5
---
Spice Garden
123 FC Road, Pune
GSTIN: 27AAAAA0000A1Z5
---
Paneer Tikka   ₹320
Dal Makhani    ₹260
---
Dear Ravi,
Your total is ₹1180.00.
Thank you for visiting!

Compare the first block (built the old way, with \n) and the second (a text block): same printed result, far easier to read in the source.

Java strips the common leading indentation using the least-indented line as the reference — usually the closing """. Indent the whole block to match your code's style; the printed text still starts at column 0.

Filling in values works with .formatted(...), which uses the same placeholders (%s, %d, %.2f, …) as String.format and printf:

String note = """
        Dear %s,
        Your total is ₹%.2f.
        Thank you for visiting!
        """.formatted(customerName, total);

A literal % inside a text block that is later .formatted(...) must be written %%, exactly like in printf.

Full program: examples/07_text_blocks.java.

Done here? The practice set for Part 2 — including the solutions — is on the part page.

Search the guide