← Back to Advanced Java Course | Chapter 4: Modern Java Features | Lesson 6 of 12

Java Text Blocks

Introduction to Text Blocks

Text blocks let you write multi-line string literals without needing backslash line-continuation characters or endless string concatenation. A text block starts and ends with three double quotes ("""), and everything between those delimiters is preserved as written, newlines included.

Example: Introduction to Text Blocks

java
public class Main {
	public static void main(String[] args) {
		String text = """
			Line one
			Line two""";
		System.out.println(text);
	}
}

Indentation Handling

Java automatically handles indentation inside a text block: at compile time, it determines the common leading whitespace shared by every line and strips exactly that much from each one. This lets you indent a text block to match your surrounding code without that indentation leaking into the actual string value.

Example: Indentation Handling

java
public class Main {
	public static void main(String[] args) {
		String text = """
				Hello
				World""";
		System.out.println(text); // common leading whitespace is stripped
	}
}

Escape Sequences

You can use ordinary double quotes inside a text block without needing to escape them, since the triple-quote delimiters remove that ambiguity. If you want to write a long logical line of text without an actual line break appearing in the output, you can end that line with a backslash (\\) to suppress the newline.

Example: Escape Sequences

java
public class Main {
	public static void main(String[] args) {
		String text = """
			She said "hello" without escaping. \
			This line joins the one above.""";
		System.out.println(text);
	}
}

Dynamic Formatting

You can format values into a text block dynamically at runtime using String.format() with the block as a template, or by calling the newer formatted() instance method directly on the text block itself for equivalent behavior with cleaner syntax.

Example: Dynamic Formatting

java
public class Main {
	public static void main(String[] args) {
		String template = """
			Name: %s
			Age: %d""";
		System.out.println(template.formatted("Zoya", 28));
	}
}

Replacing HTML Templates

Text blocks make it far easier to write and maintain embedded HTML, SQL, or JSON templates directly inside Java source code, since the multi-line structure of those formats can now be preserved visually instead of being flattened into escaped, hard-to-read single-line strings.

Example: Replacing HTML Templates

java
public class Main {
	public static void main(String[] args) {
		String html = """
			<html>
			  <body>Hello</body>
			</html>""";
		System.out.println(html);
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.