Text Blocks (Java 13–15)
Multi-line string literals, incidental whitespace stripping, formatted() method
- Write readable multi-line JSON, SQL and HTML with text blocks
- Understand incidental vs essential whitespace rules
- Apply .formatted() for inline substitution
Topics Covered:
Problems with multi-line strings · Text Block syntax · Compilation behavior · Four Text Block rules · Leading/trailing whitespace handling · Continuation character · Line terminator character · String methods on Text Blocks · formatted() for variable interpolation
Text Blocks
Overview
A Text Block is a multi-line string literal introduced as a standard feature in Java 15. It allows developers to write multi-line strings in a natural, readable format — without escape characters, string concatenation, or newline literals — by enclosing content between triple double-quote delimiters (""").
Text Blocks are particularly useful for embedding structured content in Java source code, such as SQL queries, JSON payloads, HTML, and XML.
Why This Concept Exists The Problem With Multi-Line Strings
Two Common Use Cases That Expose the Problem
Before Text Blocks, two situations in everyday Java development required writing multi-line strings: SQL queries and JSON strings (especially in test cases for validating expected output).
Problem 1 SQL Queries
1// Old way — SQL query as a multi-line string2String query = "SELECT id, name, email\n" +3 "FROM users\n" +4 "WHERE active = true\n" +5 "ORDER BY name ASC;";Problem 2 JSON Strings (in test cases)
1// Old way — expected JSON for test assertion2String expectedJson = "{\n" +3 " \"name\": \"Alice\",\n" +4 " \"country\": \"India\"\n" +5 "}";Four Problems With the Old Approach
◆ 1. Difficult to Read
Special characters clutter the actual content. The real SQL or JSON logic is buried under \n, \", and + operators. A developer reading this must mentally strip away the noise to understand the content.
◆ 2. Error Prone
1// Can you spot the bug?2String json = "{\n" +3 " \"name\": \"Alice\"\n" + // ← missing comma!4 " \"age\": 30\n" +5 "}";The missing comma after "Alice" is almost invisible among the escape characters. In plain JSON it would stand out immediately. In this string form, it blends in.
◆ 3. Hard to Maintain
Editing a multi-line string requires careful attention to ensure:
- Every
\nis still in place after a change. - Every
\"is correctly escaped. - The
+concatenation operator is present on every line.
A single misplaced character breaks the string silently (wrong content) or loudly (compile error).
◆ 4. Not Copy-Paste Friendly
You cannot copy a SQL query from a database tool and paste it directly into Java source code as a string — you must manually add \n, \", and + throughout. Conversely, extracting a string from Java code to test it elsewhere requires the reverse cleanup.
Definition
Text Block:
A Java 15 multi-line string literal delimited by """ (triple double-quotes). Everything written between the opening """ and closing """ is treated as string content. The compiler automatically handles newline characters, indentation stripping, and escape processing according to a defined set of rules, producing a regular String object at runtime.
Real-World Analogy
Think of writing an address. The old string approach is like writing it all on one line with special codes: "123 Main St\nSpringfield\nUSA". A Text Block is like writing it naturally on paper — each line on its own row — and letting the post office (the compiler) format it correctly for processing.
Syntax
1String textBlock = """2 your content here3 second line4 third line5 """;Syntax Breakdown
| Element | Explanation |
|---|---|
""" (opening) | Opening delimiter. Must be followed immediately by a newline — no content allowed on the same line. |
| Content | Written naturally across multiple lines. No escape characters needed. |
""" (closing) | Closing delimiter. Can be on its own line or at the end of the last content line. Its horizontal position controls indentation removal. |
Internal Working Text Blocks Are Just Sugar Coating
Text Blocks are a compile-time convenience only. They do not introduce a new type. After compilation, a Text Block becomes an ordinary String object — identical to what you would get from the old multi-line concatenation approach.
1// You write (Text Block):2String json = """3 {4 "name": "Alice",5 "country": "India"6 }7 """;8
9// Compiler produces (equivalent to):10String json = "{\n \"name\": \"Alice\",\n \"country\": \"India\"\n}\n";String. All String methods work identically on both.Compilation Steps
The Java compiler applies a specific sequence of transformations to a Text Block during compilation:
1Source Text Block2 ↓31. Line terminators normalized to \n4 ↓52. Incidental leading whitespace removed (indentation rule)6 ↓73. Trailing whitespace removed (unless \s is used)8 ↓94. Escape sequences interpreted10 ↓11Regular String object in .class fileThe Four Text Block Rules
These rules govern how the compiler transforms a Text Block. Understanding them is essential for predicting exactly what string you will get.
Rule 1 Opening Delimiter: No Content on the Same Line
Content must begin on the line after the opening """.
1// ✅ CORRECT — content starts on next line2String s = """3 Hello, World!4 """;5
6// ❌ COMPILE ERROR — content on same line as opening delimiter7String s = """Hello, World!8 """;9// Error: illegal text block start, missing newline after opening quotes◆ Why This Rule Exists
The compiler's job includes removing indentation (leading whitespace) from every line of content. To do this correctly, it must be able to identify what "indentation" means — i.e., how many spaces to strip from the front of each line.
If content were allowed on the same line as the opening """, the first line would have zero leading spaces while subsequent lines might have several — leaving the compiler unable to determine a consistent indentation level to remove.
1Without this rule — compiler is confused:2"""Hello ← 0 leading spaces before "Hello"3 World ← 4 leading spaces before "World"4 """5
6How many leading spaces should be removed from each line? 0? 4? Ambiguous!1With this rule — compiler is clear:2"""3 Hello ← 4 leading spaces4 World ← 4 leading spaces5 """6
7Minimum leading spaces = 4. Remove 4 from every line. Consistent!Rule 2 Indentation: Leading Whitespace Removal
All whitespace before the "leftmost" content is automatically removed.
The compiler finds the line with the fewest leading spaces among all content lines (including the closing """). That number of spaces is stripped from the beginning of every line. Any spaces beyond that minimum are preserved — they are part of the content's own internal indentation.
◆ Example Basic Indentation Removal
1public class IndentationExample {2 public static void main(String[] args) {3
4 String json = """5 {6 "name": "Alice",7 "age": 308 }9 """;10
11 System.out.println(json);12 }13}Before compilation (as written in source):
1 { ← 16 leading spaces2 "name": "Alice", ← 20 leading spaces3 "age": 30 ← 20 leading spaces4 } ← 16 leading spaces5 ← 16 leading spaces (closing """)Leftmost content: 16 spaces (the { line and } line, and the closing """).
After compiler removes 16 leading spaces from every line:
1{2 "name": "Alice",3 "age": 304}{
"name": "Alice",
"age": 30
}""" influences indentation. If you move the closing """ to the left, more whitespace is stripped. This gives you manual control over how much indentation is removed.◆ Example Controlling Indentation With Closing Delimiter Position
1// Closing """ at column 0 — maximum indentation removal2String s1 = """3 Hello4 World5""";6// Result: " Hello\n World\n" ← closing """ is leftmost; nothing removed!7
8// Closing """ aligned with content — standard removal9String s2 = """10 Hello11 World12 """;13// Result: "Hello\nWorld\n" ← 8 spaces removed from every lineRule 3 Trailing Whitespace: Removed by Default, Preserved With `\s`
All trailing whitespace (spaces at the end of a line) is removed by default.
This prevents invisible characters from accidentally entering your string, which is almost always the desired behavior.
1String s = """2 Hello, 3 World4 """;5// The spaces after "Hello," are removed → "Hello,\nWorld\n"◆ Preserving Trailing Whitespace With `\s`
If you intentionally need trailing spaces, place \s (the space escape sequence) at the end of the line. The compiler treats \s as a literal space AND uses it as a marker that tells the trailing-whitespace stripper to stop before it.
1String s = """2 Hello, \s3 World4 """;5// The \s and the spaces before it are preserved → "Hello, \nWorld\n"6// ^^^^7// spaces + \s preserved\s is equivalent to a single space character. Its primary purpose inside Text Blocks is to anchor trailing whitespace so it is not stripped.Rule 4 Line Terminators and the Continuation Character `\`
By default, each new line in a Text Block adds a \n (newline) character to the compiled string.
1String s = """2 line one3 line two4 line three5 """;6
7// Compiled result: "line one\nline two\nline three\n"◆ The Problem When You Don't Want a Newline
Sometimes you want to write long content across multiple lines for readability in your source file, but you want it to compile into a single continuous line with no \n characters. A common example is a very long URL:
1// Without continuation character — WRONG for a URL2String url = """3 https://www.example.com/api/v1/users/4 profile?param1=value1¶m2=value25 """;6// Compiled: "https://www.example.com/api/v1/users/\nprofile?param1=value1¶m2=value2\n"7// ^^^^ unwanted newline breaks the URL!◆ Solution The Line Continuation Character `\`
Place a \ at the end of a line to suppress the newline that would normally be added. The next line is treated as a continuation of the current one.
1// With continuation character — CORRECT2String url = """3 https://www.example.com/api/v1/users/\4 profile?param1=value1¶m2=value25 """;6// Compiled: "https://www.example.com/api/v1/users/profile?param1=value1¶m2=value2\n"7// ^^^^ no newline — lines are joined!◆ Another Use Case Long Readable Strings
1String message = """2 This is the first part of a very long sentence that \3 continues here without a line break in the output.4 """;5// Compiled: "This is the first part of a very long sentence that continues here without a line break in the output.\n"Rules Summary Table
| Rule | Default Behavior | How to Override |
|---|---|---|
| Opening delimiter | Content must start on the next line | Cannot be overridden (compile rule) |
| Leading whitespace | Minimum leading spaces are removed from all lines | Move closing """ left/right to control stripping |
| Trailing whitespace | All trailing spaces on each line are removed | Use \s at end of line to preserve trailing spaces |
| Line terminators | Each new line adds \n to the compiled string | Use \ at end of line to suppress the newline |
Flowchart Text Block Compilation
Code Examples
Beginner Example SQL Query
1public class TextBlockSQL {2 public static void main(String[] args) {3
4 // Old way5 String oldQuery = "SELECT id, name, email\n" +6 "FROM users\n" +7 "WHERE active = true\n" +8 "ORDER BY name ASC;";9
10 // New way — Text Block11 String newQuery = """12 SELECT id, name, email13 FROM users14 WHERE active = true15 ORDER BY name ASC;16 """;17
18 System.out.println(newQuery);19 }20}◆ Output
1SELECT id, name, email2FROM users3WHERE active = true4ORDER BY name ASC;Beginner Example JSON String
1public class TextBlockJSON {2 public static void main(String[] args) {3
4 // Old way — hard to read, error-prone5 String oldJson = "{\n" +6 " \"name\": \"Alice\",\n" +7 " \"age\": 30,\n" +8 " \"country\": \"India\"\n" +9 "}";10
11 // New way — Text Block12 String newJson = """13 {14 "name": "Alice",15 "age": 30,16 "country": "India"17 }18 """;19
20 System.out.println(newJson);21 System.out.println("Are they equal? " + oldJson.equals(newJson.stripTrailing()));22 }23}◆ Output
1{2 "name": "Alice",3 "age": 30,4 "country": "India"5}6Are they equal? trueIntermediate Example Demonstrating All Four Rules
1public class TextBlockRules {2 public static void main(String[] args) {3
4 // Rule 2: Leading whitespace removal5 // The closing """ is at 8 spaces → 8 spaces removed from every line6 String indented = """7 Hello8 World9 """;10 System.out.println("Indentation rule:");11 System.out.println(indented);12
13 // Rule 3: Trailing whitespace — default removal vs \s preservation14 String withTrailing = """15 no trailing 16 with trailing \s17 """;18 System.out.println("Trailing whitespace rule:");19 System.out.println("[" + withTrailing.lines().toList().get(0) + "]");20 System.out.println("[" + withTrailing.lines().toList().get(1) + "]");21
22 // Rule 4: Continuation character23 String singleLine = """24 This is actually \25 one single line.26 """;27 System.out.println("Continuation character rule:");28 System.out.println(singleLine);29 }30}◆ Output
1Indentation rule:2Hello3 World4
5Trailing whitespace rule:6[no trailing]7[with trailing ]8
9Continuation character rule:10This is actually one single line.Advanced Example String Methods on Text Blocks
Since Text Blocks compile to ordinary String objects, every String method works on them.
1public class TextBlockMethods {2 public static void main(String[] args) {3
4 String json = """5 {6 "language": "java",7 "version": "fifteen"8 }9 """;10
11 // toUpperCase()12 System.out.println(json.toUpperCase());13
14 // contains()15 System.out.println(json.contains("java")); // true16
17 // replace()18 System.out.println(json.replace("java", "python"));19
20 // length()21 System.out.println("Length: " + json.length());22
23 // strip()24 String stripped = json.strip();25 System.out.println("Stripped length: " + stripped.length());26 }27}◆ Output
1{2 "LANGUAGE": "JAVA",3 "VERSION": "FIFTEEN"4}5true6{7 "language": "python",8 "version": "fifteen"9}10Length: 5111Stripped length: 50Advanced Example Variable Interpolation With `formatted()`
You can embed dynamic values into a Text Block using the formatted() method (available since Java 15), which works like String.format() but called directly on the string.
1public class TextBlockFormatted {2 public static void main(String[] args) {3
4 String name = "Shreyansh";5 String country = "India";6
7 String profile = """8 {9 "name": "%s",10 "country": "%s"11 }12 """.formatted(name, country);13
14 System.out.println(profile);15 }16}◆ Output
1{2 "name": "Shreyansh",3 "country": "India"4}◆ How `formatted()` Works
%sis a format specifier forString(same as inString.format())..formatted(name, country)replaces the first%swithnameand the second%swithcountry.- The method is called directly on the Text Block literal — no intermediate variable needed.
Memory Representation
1Source Code (.java file)2┌──────────────────────────────┐3│ String s = """ │4│ Hello │ ← Text Block (human-readable)5│ World │6│ """; │7└──────────────────────────────┘8 ↓ compiler9Bytecode (.class file)10┌──────────────────────────────┐11│ String s = "Hello\nWorld\n" │ ← Regular String constant12└──────────────────────────────┘13 ↓ JVM (runtime)14Heap Memory15┌──────────────────────────────┐16│ String object │17│ value: "Hello\nWorld\n" │ ← Standard String Pool entry18└──────────────────────────────┘Text Blocks are interned in the String Pool just like any other string literal — they benefit from the same memory optimization.
Diagram Text Block vs Old Multi-Line String
Key Observations
- A Text Block is not a new type — it compiles to a
java.lang.String. - All
Stringmethods (toUpperCase(),contains(),replace(),length(),strip(),formatted(), etc.) work on Text Blocks. - Text Blocks cannot start content on the same line as the opening
""". - The closing
"""position acts as a control point for how much leading whitespace is stripped. - Trailing whitespace is silently removed by default — use
\sto preserve it. - The
\continuation character joins two physical lines into one logical line. - Text Blocks are great for: SQL, JSON, HTML, XML, regular expressions, and any content that would otherwise require heavy escaping.
nullcannot be assigned with a Text Block —String s = """null"""gives the string "null", notnull.
Common Mistakes
Mistake 1 Content on Same Line as Opening Delimiter
1// ❌ COMPILE ERROR2String s = """Hello3 World4 """;5
6// ✅ CORRECT7String s = """8 Hello9 World10 """;Mistake 2 Unexpected Indentation in Output
1public class Main {2 public static void main(String[] args) {3 // ❌ Closing """ is at column 8 — only 8 spaces removed4 // But content has 8 spaces → everything lines up at column 0 → correct5 // However, if closing """ is indented MORE than content, unexpected spaces appear6 String s = """7Hello8World9"""; // closing """ at column 0 — 0 spaces removed (nothing stripped!)10 // Result: "Hello\nWorld\n" — actually fine here!11 }12}""" with or to the left of your content start to get predictable stripping. The safest pattern is to align the closing """ with the content.Mistake 3 Forgetting That Trailing Spaces Are Removed
1// ❌ Trailing spaces silently vanish2String csv = """3 Alice, 30, 4 Bob, 25, 5 """;6// "Alice, 30," and "Bob, 25," — the trailing spaces are gone!7
8// ✅ Use \s to preserve9String csv = """10 Alice, 30, \s11 Bob, 25, \s12 """;Mistake 4 Using `+` Concatenation Inside Text Blocks
1// ❌ You cannot embed expressions inside Text Blocks (no interpolation syntax)2String name = "Alice";3String s = """4 Hello, """ + name + """!5 """;6// Ugly and defeats the purpose7
8// ✅ Use formatted() for dynamic values9String s = """10 Hello, %s!11 """.formatted(name);Mistake 5 Expecting No Trailing Newline
1String s = """2 Hello3 """;4System.out.println(s.length()); // "Hello\n" → length is 6, not 5!5// The closing """ on its own line causes a trailing \n to be included.6
7// To avoid trailing newline, put closing """ on the last content line:8String s2 = """9 Hello""";10// "Hello" → length is 5, no trailing \nBest Practices
- Use Text Blocks for all multi-line strings — SQL, JSON, HTML, XML, regex patterns.
- Align the closing
"""with the content for predictable indentation stripping. - Use
.formatted()for variable substitution instead of string concatenation. - Use
\swhenever trailing whitespace is semantically significant. - Use
\(continuation) for logically single-line content that you want to wrap for readability. - Do not use Text Blocks for single-line strings — regular string literals are cleaner for those.
- Copy-paste freely — Text Blocks are designed so you can paste real SQL or JSON directly into the source file with minimal adjustment.
Interview Notes
Commonly Asked Interview Questions on Text Blocks:
- What is a Text Block in Java and when was it introduced? — A multi-line string literal delimited by
""", finalized in Java 15. - What problem does Text Block solve? — Eliminates the need for
\n,\", and string concatenation in multi-line strings, making code more readable and less error-prone. - Is a Text Block a new type in Java? — No. It compiles to a regular
java.lang.Stringobject. It is purely a compile-time syntactic convenience (syntactic sugar). - Why can't you put content on the same line as the opening
"""? — Because the compiler needs all content to start from the next line so it can consistently determine how many leading whitespace characters to strip. - How does indentation stripping work? — The compiler finds the leftmost content position (minimum leading spaces), then strips that many spaces from the beginning of every line.
- How do you preserve trailing whitespace in a Text Block? — Use
\sat the end of the line. - What does the
\(backslash) at the end of a line do in a Text Block? — It suppresses the newline that would normally be added, joining the next line as a continuation. - Can you use String methods on a Text Block? — Yes, all
Stringmethods work identically since Text Blocks compile to regularStringobjects. - How do you embed variables in a Text Block? — Use
%s(or other format specifiers) and call.formatted(args)on the Text Block. - Where are Text Blocks stored in memory? — In the String Pool, like all string literals.
Related Concepts
String.format()— the traditional way to embed variables in strings;.formatted()is its instance-method equivalent available since Java 15.StringPool / String Interning — Text Blocks, like string literals, are stored in the pool.StringBuilder— another approach for dynamic multi-line string construction; less clean than Text Blocks for static content.- Pattern Matching (
instanceof) — another Java 16 readability/safety improvement in the same era of Java enhancements. - Escape sequences —
\n,\t,\",\\,\s— understanding these is prerequisite to understanding what Text Blocks replace.
Practice Questions
Easy
- Convert this string to a Text Block:
1 String html = "<html>\n" +2 " <body>\n" +3 " <p>Hello</p>\n" +4 " </body>\n" +5 "</html>";- What is the output of
System.out.println("""hello""".length())? (Hint: this causes a compile error — why?) - What character do you use to preserve trailing whitespace in a Text Block?
Medium
- Explain what happens to the leading whitespace in this Text Block and what the output will be:
1 String s = """2 Hello3 World4 """;5 System.out.println(s);- Write a Text Block that produces the string
"Hello World"(single line, no\n) even though it is written across two lines in source code. - Given a Text Block with trailing spaces after some lines, how would you selectively preserve spaces on only some lines?
Hard
- Consider two Text Blocks where the closing
"""is at different indentation levels. Predict the exactStringoutput for each and explain why they differ. - Write a method
buildJsonPayload(String name, int age, String city)that returns a formatted JSON string using a Text Block. - Why does
"""hello"""cause a compile error while"""hello\n"""would compile (albeit with an equivalent error message)? What is the exact rule being violated?
Summary
| Key Point | Detail |
|---|---|
| Java version | Finalized in Java 15 (preview in 13, 14) |
| Delimiter | """ (triple double-quote) on both ends |
| New type? | No — compiles to java.lang.String |
| Rule 1 | No content on same line as opening """ |
| Rule 2 | Leading whitespace stripped up to leftmost content |
| Rule 3 | Trailing whitespace removed by default; use \s to preserve |
| Rule 4 | Each new line adds \n; use \ to suppress and continue |
| Variable values | Use .formatted() with %s, %d, etc. |
| String methods | All String methods work — toUpperCase(), replace(), etc. |
| Memory | Stored in String Pool like any literal |
| Use for | SQL, JSON, HTML, XML, long URLs, test expected values |
\n, +, or \", stop and use a Text Block instead. Your future self (and your teammates) will thank you.End of Chapter — Java 15: Text Blocks
Mastery check
How well can you recall this?
Finished this lesson?