Video in progress
What are compact strings in Java 9, and how is data stored inside a String?
Since Java 9, a String holds a byte[] and a coder instead of a char[]. If every character fits in Latin-1, it's 1 byte per character; if not, it's 2 bytes in UTF-16.
📖 Answer
Up to Java 8, every String held a char[]: 2 bytes per character, even for "hello". If you open a heap dump, strings are often eating a big chunk of memory. That's why JEP 254 changed the internal structure:
// simplified view
final byte[] value;
final byte coder; // LATIN1 = 0, UTF16 = 1
What changed in practice:
- ASCII/Latin-1 text (JSON keys, ids, logs) takes half the memory;
- if the text contains a single Cyrillic character or an emoji, the whole string is stored in UTF-16;
length()still returns the number of UTF-16 code units: the API didn't change.
Uzbek Latin text (o', g') fits in Latin-1, but Cyrillic text doesn't, so they differ in memory use.
It's on by default; you can turn it off with -XX:-CompactStrings, but you almost never need to. Another related optimization is -XX:+UseStringDeduplication in G1: it makes strings with identical content share one internal array, but it doesn't merge the objects themselves.
Sign up to mark studied questions and save your progress.