Java / Java 21 Coding Standards Interview Questions
When should you choose text blocks over string concatenation?
A text block is the standard choice once a string literal spans more than roughly two or three lines, or contains embedded quotes, because concatenation with + and escaped \" characters quickly becomes hard to read and easy to get subtly wrong.
// concatenation String sql = "SELECT id, name " + "FROM customers " + "WHERE status = 'ACTIVE'"; // text block String sql = """ SELECT id, name FROM customers WHERE status = 'ACTIVE'""";
Text blocks are especially favored for embedded SQL, JSON payloads, and HTML fragments in test fixtures, where preserving the exact multi-line shape of the literal makes the code read like the artifact it produces.
Concatenation is still the right tool for short, single-line strings or when the content is built dynamically from variables using formatted interpolation-style calls such as String.format, since a text block is meant for a mostly-static, multi-line literal, not for assembling small runtime fragments.
More Related questions...