3.5 Text Blocks & Compact Strings
← Back to Chapter 3: Strings in Java
Modern Java includes major compiler and JVM-level enhancements designed to simplify multi-line string authoring and halve heap memory overhead.
1. Text Blocks (Java 15 LTS)
Text Blocks provide a clean syntax for multi-line string literals (JSON, SQL, HTML) delimited by triple quotes """:
// Legacy String: Horrid concatenation and manual escape sequences
String oldJson = "{\n" +
" \"name\": \"Sarwvidya\",\n" +
" \"role\": \"Developer\"\n" +
"}";
// Modern Java Text Block: Clean, formatted, zero escaping required!
String newJson = """
{
"name": "Sarwvidya",
"role": "Developer"
}
""";
Incidental Whitespace Stripping
The Java compiler automatically calculates the minimum common indentation of all non-empty lines and strips it away. The position of the closing """ controls whether trailing or leading indentation is preserved.
Escape Sequences in Text Blocks
\at end of line: Suppresses the trailing newline (line continuation).\s: Preserves explicit trailing whitespace that would otherwise be trimmed.
2. Compact Strings (Java 9 JVM Optimization)
Historically (Java 1.0 to 8), every java.lang.String stored characters inside a char[] array:
// Prior to Java 9: Every char consumed 16 bits (2 bytes), even for pure ASCII
private final char value[];
Studies showed that in enterprise heaps, strings accounted for ~25% of total live memory, and over 85% of those strings contained only single-byte ASCII characters.
The Compact Strings Solution (JEP 254)
From Java 9 onwards, String internally uses a byte[] array combined with an encoding flag coder:
public final class String {
private final byte[] value;
private final byte coder; // 0 = LATIN1 (1 byte/char), 1 = UTF16 (2 bytes/char)
}
- If all characters fit into ISO-8859-1 (Latin-1 / ASCII), each character occupies only 1 byte.
- If any character requires Unicode (e.g. Emoji, Devanagari, Japanese), the JVM automatically switches to UTF-16 (2 bytes per character).
- Result: Immediate 30–50% memory reduction in String allocations across all applications with zero code changes!