Text Blocks — Multi-line Strings
Use Java text blocks for readable multi-line strings: SQL, JSON, HTML, and formatted templates.
public class TextBlocks {
// SQL query
static String query = """
SELECT u.name, u.email, COUNT(o.id) AS order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.status = 'active'
AND u.created_at > ?
GROUP BY u.name, u.email
HAVING COUNT(o.id) > 5
ORDER BY order_count DESC
""";
// JSON template
static String jsonTemplate(String name, String email) {
return """
{
"name": "%s",
"email": "%s",
"role": "user",
"active": true
}
""".formatted(name, email);
}
// HTML
static String html = """
<html>
<head><title>Report</title></head>
<body>
<h1>Monthly Report</h1>
<p>Generated at: %s</p>
</body>
</html>
""";
// Regex pattern
static String emailRegex = """
^[a-zA-Z0-9._%+-]+\
@[a-zA-Z0-9.-]+\
\\.[a-zA-Z]{2,}$""";
public static void main(String[] args) {
System.out.println(query);
System.out.println(jsonTemplate("Alice", "alice@test.com"));
// String methods with text blocks
String csv = """
name,age,city
Alice,30,NYC
Bob,25,LA
""";
csv.lines()
.skip(1) // skip header
.map(line -> line.split(","))
.forEach(parts -> System.out.printf("%s is %s%n", parts[0], parts[1]));
}
}Use Cases
- Embedding SQL queries in Java code
- JSON and HTML template strings
- Readable multi-line configuration strings
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Java Records — Immutable Data Classes
Use Java records for concise immutable data carriers with built-in equals, hashCode, and toString.
Best for: Replacing verbose POJO classes with concise records
Sealed Classes and Pattern Matching
Use sealed interfaces with pattern matching switch for type-safe, exhaustive algebraic data types.
Best for: Type-safe state machines and event handling
Switch Expressions — Modern Java
Use switch expressions with arrow syntax, pattern matching, guards, and yield for concise branching.
Best for: Concise branching logic replacing verbose if-else
Pattern Matching for instanceof
Use modern Java pattern matching with instanceof, guarded patterns, and record deconstruction.
Best for: Type-safe polymorphic processing