Video in progress
What is a text block (""" ... """), and where is it handy?
A text block (Java 15+) is a way to write a multi-line string without escape characters (\n, \"). It's handy for text like SQL, JSON and HTML; the common leading whitespace is stripped automatically.
📖 Answer
Before:
String json = "{\n" +
" \"name\": \"Ali\",\n" +
" \"age\": 25\n" +
"}";
With a text block:
String json = """
{
"name": "Ali",
"age": 25
}
""";
The rules:
- the line has to end right after the opening
"""; - the common indentation is removed, based on the closing
"""or the leftmost line; - trailing spaces at the end of a line are removed; if you need to keep them, use
\s; - to continue a long line without breaking it, put a
\at the end of the line.
Inserting values:
String sql = """
select * from orders
where status = '%s'
""".formatted(status);
But be careful: adding a value to SQL like this is SQL injection. A text block is only for writing the query template, and the values should still be passed as PreparedStatement parameters.
Sign up to mark studied questions and save your progress.