Nearby lessons

100 of 125

Java - Text Blocks

📌 What You Will Learn
  • Text blocks — the first preview
  • Switch expressions with yield
  • String.formatted()
  • The idea of preview iterations

Text Blocks is a core concept of the Java language. This lesson explains Java 13 — Text Blocks Arrive, Text Blocks — Clean Multi-line Strings and Text Blocks — Second Preview with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Java 13 — Text Blocks Arrive

Java 13 (September 2019) continued the switch expression journey and introduced the most loved new feature for developers: Text Blocks (as a preview). Writing multi-line strings in Java had always been painful — Java 13 fixed it.

Text Blocks — Clean Multi-line Strings

A text block is a String written over many lines using three double-quotes. No more "\n" and + everywhere:

Example02
JCode Cell
1// OLD - painful multi-line String
2String html = "<html>\n" +
3 " <body>\n" +
4 " <h1>Hello</h1>\n" +
5 " </body>\n" +
6 "</html>";

Text Blocks — Clean Multi-line Strings

Text blocks are perfect for: SQL queries, JSON data, HTML templates, and any long text in code. The indentation is handled automatically — Java removes the common leading spaces of all lines.

In simple words: A text block is just a String that can span many lines. You write it with three double quotes, and Java removes the indentation common to all lines so the string looks exactly as you would print it.
Example03
JCode Cell
1// NEW - text block (Java 13+)
2String html = """
3 <html>
4 <body>
5 <h1>Hello</h1>
6 </body>
7 </html>
8 """;
9 
10System.out.println(html);
Output
<html> <body> <h1>Hello</h1> </body> </html>

Text Blocks — Clean Multi-line Strings

Example04
JCode Cell
1String sql = """
2 SELECT name, marks
3 FROM student
4 WHERE marks > 40
5 ORDER BY name
6 """;

Text Blocks — Second Preview

Java 14 improved text blocks again (new escape sequences like \s to keep spaces and \ to break a line) before they became final in Java 15.

Example05
JCode Cell
1String poem = """
2 Roses are red,
3 Violets are blue.
4 """;

Text Blocks — Modern Multi-line Strings

Updated knowledge (Java 15+): writing long multi-line text was painful with quotes and + signs. Java 15 made it easy with text blocks using triple quotes:

Example06
JCode Cell
1String html = """
2 <html>
3 <body>
4 <h1>Welcome</h1>
5 </body>
6 </html>
7 """;
8System.out.println(html);
📝 Key Takeaways
  • Text blocks (""" ... """) give clean multi-line Strings for HTML, SQL, JSON.
  • Switch expressions got yield for block-style cases.
  • formatted() formats a text block's placeholders.
  • Text blocks became final in Java 15; switch expressions in Java 14.
  • Preview iterations show how Java matures features carefully.

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8