Text Blocks for Multi-line Strings
Demonstrates Java text blocks for multi-line string literals with proper indentation handling, template formatting, and SQL/JSON/HTML generation.
Code
public class TextBlocksFormatting {
public static void main(String[] args) {
String json = """
{
"name": "Alice",
"age": 30,
"skills": ["Java", "Python"],
"active": true
}
""";
System.out.println("JSON:");
System.out.println(json);
String sql = """
SELECT u.name, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.active = true
GROUP BY u.name
HAVING COUNT(o.id) > 0
ORDER BY order_count DESC
""";
System.out.println("SQL:");
System.out.println(sql);
String html = """
<div class="card">
<h2>%s</h2>
<p>%s</p>
</div>
""".formatted("Welcome", "Hello, World!");
System.out.println("HTML:");
System.out.println(html);
String indented = """
Line 1
Line 2
Line 3
""".stripIndent();
System.out.println("Stripped: [" + indented + "]");
String escaped = """
Escaped: \"quote\"
Newline: \n is literal
""";
System.out.println(escaped);
}
}Inside the snippet
Count the class TextBlocksFormatting and the function main as the entire surface area of Text Blocks for Multi-line Strings.
Using it
Running the file prints labeled results such as JSON:, SQL:, HTML: — each operation’s effect is visible in the output.
Key statements
""".formatted("Welcome", "Hello, World!");
SELECT u.name, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.active = true
GROUP BY u.name
HAVING COUNT(o.id) > 0
ORDER BY order_count DESC
""";
Newline: \n is literal
""";
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- What does Text Blocks for Multi-line Strings print when run?
- Invoke the file as-is — the `JSON:`, `SQL:`, `HTML:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.