formatted(), stripIndent() and translateEscapes()
formatted() is fine for this demo; real queries must pass user values as PreparedStatement parameters, not by formatting.
A text block is a multi-line String literal written between triple quotes ("""). It keeps your line breaks, removes the indentation that only exists to line the code up, and needs almost no escaping, which makes JSON, SQL, HTML and test data readable in Java code.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Use a text block to print a small receipt with three items and a total, with the item names left-aligned. The output must have no leading spaces.
Write a text block whose output lines are indented by exactly 4 spaces, without typing 4 extra spaces on each content line. Show it with visible()-style dots.
Rewrite "Dear " + name + ",\n\nYour order " + id + " has shipped.\n" as a text block with formatted. Print it for Ravi and A-42.
Explain it without notes
What is a text block and what rules apply to its opening and closing delimiters?
How does the compiler decide how much indentation to remove?
In which order does javac process a text block, and why does the order matter?
What do the \s and \<line-end> escapes do?
How do you put variable values into a text block?
Expected output
SELECT id, name
FROM users
WHERE city = 'Pune'
AND age > 18
alpha
beta
gamma
before: line one\nline two
after translateEscapes:
line one
line two