Java Text Blocks
In this page:
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
public class Main {
public static void main(String[] args) {
String text = """
Line one
Line two""";
System.out.println(text);
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
String text = """
Hello
World""";
System.out.println(text); // common leading whitespace is stripped
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
String template = """
Name: %s
Age: %d""";
System.out.println(template.formatted("Zoya", 28));
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
String html = """
<html>
<body>Hello</body>
</html>""";
System.out.println(html);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: