Java 17: Build multi-line SQL and JSON with text blocks. Compare concatenation, StringBuilder and text blocks safely.
Problem
Embed a multi-line SQL query and a JSON payload template in code. Interviewers check text block rules and, importantly, that you do not create SQL injection.
Approach 1: Concatenation with \n (Java 8)
Noisy quotes and escapes; easy to lose a space between lines.
class SqlConcat {
static final String QUERY =
"SELECT o.id, o.total, c.name\n" +
"FROM orders o\n" +
"JOIN customer c ON c.id = o.customer_id\n" +
"WHERE o.status = ? AND o.created_at > ?\n" +
"ORDER BY o.created_at DESC";
}Approach 2: String.join or StringBuilder
Cleaner for dynamic pieces, still not readable as SQL.
class SqlJoin {
static final String QUERY = String.join("\n",
"SELECT o.id, o.total, c.name",
"FROM orders o",
"JOIN customer c ON c.id = o.customer_id",
"WHERE o.status = ? AND o.created_at > ?",
"ORDER BY o.created_at DESC");
}Approach 3: Text block (Java 15+, in Java 17 LTS)
""" starts on its own line; incidental indentation (the common leading whitespace) is stripped automatically; the closing delimiter's position controls indentation and trailing newline. Escapes: \ at end of line joins lines, \s keeps a trailing space, \""" embeds triple quotes.
class SqlTextBlock {
static final String QUERY = """
SELECT o.id, o.total, c.name
FROM orders o
JOIN customer c ON c.id = o.customer_id
WHERE o.status = ? AND o.created_at > ?
ORDER BY o.created_at DESC"""; // closing quotes on the last line: no trailing newline
static final String ONE_LINE = """
This is one long sentence \
written over two lines.""";
// Template with placeholders filled by formatted() (Java 15)
static final String WELCOME_EMAIL = """
Hi %s,
Your order %s is confirmed.
Total: %s
""";
}Approach 4: Text block plus safe parameters (the correct production answer)
Never formatted() or concatenate user input into SQL or JSON. Keep ? placeholders and bind values with PreparedStatement (or NamedParameterJdbcTemplate, JPA parameters), and build JSON with a library (Jackson) or at least escape values.
import java.time.LocalDate;
class TextBlockDemo {
// Minimal JSON string escaping for the demo; in real code use Jackson's ObjectMapper
static String json(String s) { return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\""; }
static String orderJson(String id, String customer, long totalPaise) {
return """
{
"id": %s,
"customer": %s,
"totalPaise": %d
}""".formatted(json(id), json(customer), totalPaise);
}
public static void main(String[] args) {
System.out.println(SqlConcat.QUERY.equals(SqlTextBlock.QUERY) && SqlJoin.QUERY.equals(SqlTextBlock.QUERY)); // true
System.out.println(SqlTextBlock.ONE_LINE);
System.out.print(SqlTextBlock.WELCOME_EMAIL.formatted("Asha", "o-17", "INR 1,250"));
System.out.println(orderJson("o-17", "Asha \"AK\" Kumar", 125000));
// With JDBC the values are bound, never concatenated:
// try (PreparedStatement ps = conn.prepareStatement(SqlTextBlock.QUERY)) {
// ps.setString(1, "PAID"); ps.setObject(2, LocalDate.now().minusDays(30)); ...
// }
System.out.println(LocalDate.of(2026, 11, 1).minusDays(30));
}
}Feasible → optimal
Concatenation and String.join are feasible; text blocks are the readable default for embedded SQL, JSON, HTML or test fixtures. Correctness and security come from parameter binding and proper serialisation, not from the string syntax.
Follow-up questions interviewers ask
Try answering each one before you open it.
How does the compiler decide the indentation of a text block?
It finds the minimum indentation across all non-blank content lines and the closing delimiter line, then removes that much from every line ("incidental whitespace"). Moving the closing """ left adds indentation to the content; putting it at the end of the last content line removes the trailing newline. stripIndent() and translateEscapes() expose the same algorithms as methods.
Why is `"... WHERE name = '%s'".formatted(name)` dangerous?
If name is x' OR '1'='1, the query's meaning changes: classic SQL injection. Placeholders send the SQL and the values separately to the database, so values can never be interpreted as SQL. The same applies to JSON or HTML templates (injection and XSS), so use proper encoders.