1. The Hook (The "Byte-Sized" Intro)
- In a Nutshell: Text blocks (Java 15+) = multi-line strings with triple quotes ("""). Auto-indentation (removes incidental whitespace). Escape sequences (\n, \t still work). formatted() method for interpolation.
- Perfect for: SQL, JSON, HTML, multi-line text.
- Benefits: Readable code, no string concat, no escape hell.
- Syntax: Start """ on new line, end """ aligned with content. Incidental whitespace = common leading spaces (auto-removed). Essential whitespace = preserved!
Think of writing on lined paper. Old strings = writing sideways on one line with \n symbols (messy!). Text blocks = writing normally across lines (natural). Margins auto-align!
2. Conceptual Clarity (The "Simple" Tier)
💡 The Analogy
- Old string concat: Typing essay in single line with manual line breaks
- Text block: Using word processor (natural multi-line, auto-formatting)
3. Technical Mastery (The "Deep Dive")
Text Block Rules
| Rule | Description |
|---|---|
| Triple quotes | """ to start and end |
| Start on new line | Opening """ must be followed by newline |
| Auto-indent | Common leading whitespace removed |
| Escape sequences | \n, \t, \" still work |
| Line terminators | Normalized to \n |
4. Interactive & Applied Code
java
public class TextBlocksDemo {
public static void main(String[] args) {
demonstrateBasics();
demonstrateIndentation();
demonstrateSQL();
demonstrateJSON();
demonstrateHTML();
}
// ❌ BEFORE: Traditional strings (escape hell!)
static void oldWay() {
String json = "{\n" +
" \"name\": \"Alice\",\n" +
" \"age\": 30\n" +
"}";
System.out.println(json);
}
// ✅ AFTER: Text blocks (clean!)
static void newWay() {
String json = """
{
"name": "Alice",
"age": 30
}
""";
System.out.println(json);
}
static void demonstrateBasics() {
System.out.println("=== BASIC TEXT BLOCKS ===");
// Simple multi-line text
String poem = """
Roses are red,
Violets are blue,
Java is awesome,
And so are you!
""";
System.out.println(poem);
// Preserves formatting
String formatted = """
This line is indented
And this one less
This one even less
""";
System.out.println(formatted);
}
// Indentation rules
static void demonstrateIndentation() {
System.out.println("\n=== INDENTATION ===");
// Incidental whitespace removed (based on closing """)
String text1 = """
Line 1
Line 2
"""; // Closing """ determines indent level
System.out.println("Text1: [" + text1 + "]");
// Different closing position
String text2 = """
Line 1
Line 2
"""; // Less indented closing = preserves more spaces
System.out.println("Text2: [" + text2 + "]");
// Explicit line ending (no newline at end)
String text3 = """
Line 1
Line 2\
"""; // Backslash escapes newline
System.out.println("Text3: [" + text3 + "]");
}
// Real-world: SQL queries
static void demonstrateSQL() {
System.out.println("\n=== SQL QUERIES ===");
// ❌ OLD: Concatenation nightmare
String oldQuery = "SELECT u.id, u.name, o.total\n" +
"FROM users u\n" +
"JOIN orders o ON u.id = o.user_id\n" +
"WHERE u.status = 'active'\n" +
"ORDER BY o.total DESC";
// ✅ NEW: Clean and readable
String query = """
SELECT u.id, u.name, o.total
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE u.status = 'active'
ORDER BY o.total DESC
""";
System.out.println(query);
}
// Real-world: JSON
static void demonstrateJSON() {
System.out.println("\n=== JSON ===");
String name = "Alice";
int age = 30;
// With formatted() (like String.format)
String json = """
{
"name": "%s",
"age": %d,
"active": true
}
""".formatted(name, age);
System.out.println(json);
}
// Real-world: HTML
static void demonstrateHTML() {
System.out.println("\n=== HTML ===");
String title = "Welcome";
String content = "Hello, World!";
String html = """
<!DOCTYPE html>
<html>
<head>
<title>%s</title>
</head>
<body>
<h1>%s</h1>
<p>This is a multi-line HTML template.</p>
</body>
</html>
""".formatted(title, content);
System.out.println(html);
}
}
// Advanced examples
class AdvancedTextBlocks {
public static void main(String[] args) {
// Escape sequences still work
String withEscapes = """
Line 1\tTabbed
Line 2\nExtra newline above
Quote: \"Hello\"
""";
System.out.println(withEscapes);
// stripIndent() - remove incidental whitespace
String text = """
Hello
World
""".stripIndent();
// translateEscapes() - process escape sequences
String raw = """
Line 1\\nLine 2
""".translateEscapes();
// Regex patterns (great for text blocks!)
String regex = """
^\\d{3}-\\d{2}-\\d{4}$ # SSN format
""";
}
}5. The Comparison & Decision Layer
| Scenario | Old Strings | Text Blocks |
|---|---|---|
| SQL queries | Concat + \n | Natural formatting |
| JSON/XML | Escape " everywhere | Clean structure |
| HTML templates | Unreadable | Readable |
| Regex | Double escaping | Clear patterns |
6. The "Interview Corner" (The Edge)
The "Killer" Interview Question:
"How does indentation work in text blocks?"
Answer: Closing """ position determines indent removal!
java
// Example 1: Closing """ at column 0
String text1 = """
Line 1 // 8 spaces
Line 2 // 8 spaces
"""; // Closing at column 0
// Result: " Line 1\n Line 2\n" (all 8 spaces kept)
// Example 2: Closing """ at column 8
String text2 = """
Line 1 // 8 spaces
Line 2 // 8 spaces
"""; // Closing at column 8
// Result: "Line 1\nLine 2\n" (8 spaces removed from both)
// Rule: Minimum indent of all non-blank lines AND closing """Pro-Tips:
- Line continuation (no newline):
java
String text = """
This is a very long line that \
continues on the next line
""";
// Result: "This is a very long line that continues on the next line\n"- formatted() vs format():
java
// ✅ Fluent: formatted()
String s1 = """
Hello %s
""".formatted("World");
// ✅ Static: format()
String s2 = String.format("""
Hello %s
""", "World");