Command Palette

Search for a command to run...

Back to the lesson: Topic 6.5 — Text Blocks
Core Java · Example 1 of 3 Java 15+

A JSON text block is just a String

Both are compile-time constants with identical contents, so they are the same interned object. Never rely on == for real comparisons.

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.

01

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.

02

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.

03

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

01

What is a text block and what rules apply to its opening and closing delimiters?

02

How does the compiler decide how much indentation to remove?

03

In which order does javac process a text block, and why does the order matter?

04

What do the \s and \<line-end> escapes do?

05

How do you put variable values into a text block?

A JSON text block is just a String Java 15+
Sign in to run this example in your browser.

Expected output

{
  "name": "Asha",
  "city": "Pune"
}
equals classic literal: true
same pooled object: true
lines: 4
ends with a newline: true
length: 39