Java Multiline String: Text Blocks and Alternatives
Learn practical techniques for multiline strings in Java, including text blocks, concatenation, formatting, escaping, and alternatives for older Java versions.

Writing multiline strings in Java has historically been awkward, requiring concatenation or escaped newlines. Since Java 15, text blocks (three double quotes, """) provide a native way to write them. This article covers the syntax, formatting, escaping, and alternatives for multiline strings in Java, along with practical considerations for production code.
Text blocks are a compile-time feature; they are not a new runtime type. A text block always produces a java.lang.String instance, just like a string literal. The compiler processes the content with a specific algorithm that handles incidental whitespace, line endings, and escape sequences, making them ideal for multi-line SQL, JSON, HTML, or code snippets.
Text Block Syntax and Basic Usage
To create a text block in the common form, open with three double quotes """ followed by a newline, write the content, and close with """ on its own line. The closing delimiter can also be placed at the end of the final content line, but the indentation algorithm is easier to reason about when the closing delimiter is on its own line.
String query = """
SELECT id, name
FROM users
WHERE status = 'active'
""";
System.out.println(query);In this example, the compiler strips the common indentation (the four spaces before each line) because the closing delimiter is indented four spaces. Without that indentation on the closing delimiter, the compiler would strip nothing, leaving all leading spaces in the string. This behavior is consistent: the algorithm removes the minimum number of leading spaces across all non-blank lines, and also considers the indentation of the closing delimiter.
The resulting string is "SELECT id, name\nFROM users\nWHERE status = 'active'\n" (note the trailing newline). This trailing newline is a common source of surprise; if you don't want it, you can place the closing delimiter on the same line as the last content character, but that is often less readable.
Understanding Incidental Whitespace and Indentation
The text block algorithm distinguishes between incidental and significant whitespace. Incidental whitespace is the indentation that is common to all lines, used for code readability. It is removed. Significant whitespace is any additional indentation beyond that common base, which is preserved.
Consider this example where we want to preserve extra indentation for a second line:
String sql = """
SELECT *
FROM orders
WHERE total > 100
""";The common indentation (8 spaces) is stripped, leaving "SELECT *\n FROM orders\nWHERE total > 100\n". The two extra spaces before FROM are significant and kept. This mechanism gives you precise control over indentation within the string.
If you accidentally misalign the closing delimiter, you may get more indentation than intended. If the closing delimiter is less indented than the content lines, the common indentation is lower, so the content retains more leading spaces. If the closing delimiter is more indented than the content, it does not increase the amount stripped; the common indentation is still the minimum indentation among the content lines and the closing delimiter. The compiler does not throw an exception for this; the behavior is purely the result of the stripping algorithm.
Escape Sequences in Text Blocks
Text blocks support the same escape sequences as string literals, but crucially, they add two new escapes: \s (single space) and \ (line continuation).
\sinserts a single space without ending the line. It is useful when you need a trailing space, which is otherwise trimmed by the compiler. For example, to create a string ending with a space before a newline, you can writeline1\s\nline2.\(backslash at the end of a line) suppresses the line terminator. This allows you to break a long line within the text block without introducing an actual newline in the resulting string.
String message = """
This is a very long line that continues \
here—the newline is suppressed.
""";The resulting string is "This is a very long line that continues here—the newline is suppressed.\n". Note that the indentation of the second line is still stripped as incidental, so the continuation appears flush with the first line.
These escapes are particularly useful when building formatted text where you need precise whitespace control, such as generating Java source code or SQL with alignment.
Formatting Multiline Strings with Dynamic Values
Static text blocks are useful, but most real-world strings need dynamic values. A common mistake is attempting to use String.format directly on a text block that contains % characters (for example, SQL LIKE patterns). In a format string, % introduces a format specifier, so literal percent signs must be escaped as %%. You can use a text block as the format string, but check every % in the content.
A safer approach is to use String.replace or a placeholder scheme that does not conflict with the text block content. For instance, use template placeholders like {name} and then replace them:
String template = """
SELECT * FROM users
WHERE name = '{name}' AND age > {age}
""";
String result = template
.replace("{name}", "Alice")
.replace("{age}", "25");This avoids the % escaping issue and is more readable. However, if the replacement values contain characters that are special to the target format (such as quotes or backslashes), they are inserted literally; you still need to escape them for the target format.
For more structure, Java's String.formatted(Object... args) method (added in Java 15) works on text blocks just like String.format. It respects the format specifiers and the text block content, but you must escape any literal % in the template. For example, a SQL query with a LIKE clause containing % must be written as %% in the format string.
Alternatives to Text Blocks for Older Java Versions
If you are constrained to Java 8 or 11, text blocks are unavailable. Several legacy patterns exist, each with tradeoffs.
- String concatenation with
+– This is straightforward but messy for multi-line strings. Each line needs quotes and newline escapes:
String s = "SELECT id, name\n" +
"FROM users\n" +
"WHERE status = 'active'\n";This works, but it is error-prone and hard to maintain for long strings. The indentation is manually handled, leading to inconsistent formatting.
StringBuilder– Better for efficiently building strings in loops, but for a static multiline string, it is more verbose:
StringBuilder sb = new StringBuilder();
sb.append("SELECT id, name\n");
sb.append("FROM users\n");
sb.append("WHERE status = 'active'\n");
String s = sb.toString();String.join– Concise, but you lose control over the final line terminator:
String s = String.join("\n", "SELECT id, name", "FROM users", "WHERE status = 'active'");
// Add trailing newline if needed
s = s + "\n";- Reading from a file or resource – For very large static blocks, loading from a resource file is a viable option, especially when the content is not code-related. This keeps the Java source file free from huge blocks, but it adds a runtime dependency on the resource being available on the classpath.
Each method has its use case. For short strings, concatenation is acceptable; for larger static content, text blocks are preferable, and for dynamic construction, StringBuilder or join is common.
Practical Example: Building a JSON Payload
A common real-world requirement is constructing a JSON body for an HTTP request. Text blocks make this much more readable than concatenation.
String jsonBody = """
{
"user": {
"name": "Alice",
"email": "alice@example.com"
}
}
""";The indentation is stripped correctly, and the string is valid JSON. If you need to insert dynamic values, use String.formatted with care:
String jsonBody = """
{
"user": {
"name": "%s",
"email": "%s"
}
}
""".formatted(name, email);But notice that the %s placeholders are directly in the content. If the values contain quotes or newlines, the resulting JSON will be invalid. In that case, you must escape the values before insertion, for example by using a JSON library to build the object and then convert to string. Text blocks only help with the formatting of the surrounding structure, not with the escaping of embedded data.
Performance and Compile-Time Behavior
Text blocks do not introduce runtime overhead compared to plain string literals. The compiler transforms them into string constants, and the String object is interned just like any other literal. There is no runtime parsing for newlines; the newlines are actual characters in the string. The indentation stripping occurs at compile time, so no runtime cost is incurred.
One notable performance consideration is that String.format and String.formatted are not free—they parse the format string and produce a new string. If you are generating the same JSON payload repeatedly with different values, you might want to cache the template and use MessageFormat or a template engine, but for most cases, the overhead is negligible.
Common Pitfalls and Edge Cases
Trailing newline – As noted, text blocks add a trailing newline unless you control the placement of the closing delimiter. If you need no trailing newline, you can place the closing delimiter on the same line as the last content, but that reduces readability. Alternatively, you can use String.stripTrailing() to remove trailing whitespace, but be aware that it removes all trailing whitespace, not just the newline.
Leading whitespace – If you indent the content lines with spaces but the closing delimiter is flush left, the common indentation becomes zero, and all those leading spaces are preserved. This often leads to unexpected spaces at the beginning of each line.
Windows vs Unix line endings – The compiler normalizes line endings to \n (LF) within the text block. If you run the same source on Windows, the \n is still inserted; there is no platform-dependent behavior. This is beneficial for consistency across platforms.
Escaping sequences – Within a text block, you still need to escape backslashes that are part of escape sequences, and you must escape a sequence of three double quotes if it appears in the content. Individual double quotes do not need escaping, and newlines are literal rather than \n. Be careful with content such as Windows file paths: because \ introduces an escape sequence, a literal backslash must be written as \\ in the source. For example, the source C:\\temp\\file.txt produces the final string C:\temp\file.txt.
Java version compatibility – Text blocks are a standard feature from Java 15 onward. They are not available in earlier versions. If you are working on a codebase that must compile with Java 11, you must stick with concatenation or a helper method. This is a significant factor when deciding whether to adopt text blocks in a project.
When to Use Which Approach
The best approach depends on the context and Java version.
- If you are on Java 15+ and the string is static and part of the source, use a text block. They are the most readable and least error-prone.
- If you need to construct a string dynamically in a loop,
StringBuilderis the appropriate tool because it avoids the overhead of repeated string concatenation, though for a handful of lines it doesn't matter. - If you are generating a string that mixes static and dynamic parts, a text block as a template with
String.formattedor a placeholder replacement is effective. However, ensure that the dynamic content is properly escaped for the target format. - If the string is large and not tied to the source code (for example, a long HTML template), loading it from a resource file might be more maintainable, as it allows the string to be edited by non-Java tools.
In all cases, the goal is to keep the code readable and the string correct. Text blocks significantly reduce the chance of missing a newline or misplacing a quote, which are common bugs with concatenation.
Tooling and IDE Support
Modern Java IDEs (IntelliJ IDEA, Eclipse, NetBeans) fully support text blocks, including syntax highlighting and automatic indentation adjustments. The java compiler does not require special flags; text blocks are part of the language specification. Some static analysis tools and code formatters have their own rules for indenting text blocks, and early versions of some tools had formatting bugs, but most have been resolved. If you are using an older IDE version, you may encounter formatting issues, so consider updating your toolchain.
The Java language specification defines the exact algorithm for stripping incidental whitespace. Understanding this algorithm is essential for avoiding pitfalls with indentation.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.