DEV Community

Adetayo Akinsanya
Adetayo Akinsanya

Posted on Originally published at unkletayo.dev on

Strings: what Java actually stores

Strings: what Java actually stores

String a = "hello";
String b = "hello";
System.out.println(a == b); // true

Enter fullscreen mode Exit fullscreen mode

In Objects, equality and identity, we established that == compares addresses. These two variables were not assigned from each other, yet they point to the same object. The explanation involves what a String stores internally and a structure the JVM maintains for string literals.

What a String stores

A String object holds its character data in a private final byte[] value field plus a single private final byte coder field. The coder is either 0 (Latin-1) or 1 (UTF-16).

This is a HotSpot implementation detail introduced in Java 9 as compact strings (JEP 254). Before Java 9, String stored characters in a char[], always in UTF-16, always two bytes per character. The new layout stores characters in the Unicode range U+0000 to U+00FF (ASCII and most Western European characters) at one byte each. Only when a string contains characters outside that range does the storage switch to UTF-16, using two bytes per character throughout.

What this means in practice: "hello" takes 5 bytes of character data. "hēllo" takes 10 bytes because ē (U+0113) is outside the Latin-1 range. The character é (U+00E9) is within that range and still stores at one byte. For server-side code that mainly handles ASCII text (identifiers, URLs, JSON keys), compact strings roughly halve the memory that the JVM would have used before Java 9.

The Java Language Specification says nothing about byte arrays. From the language's perspective, String is a sequence of char values. The internal storage is an OpenJDK detail, invisible through any public API. What the JLS does guarantee: String is final. You cannot subclass it. That prevents a subclass from modifying the character data while the superclass believes it is immutable.

Why String is immutable

Once a String object is created, neither the array reference nor the array contents change. No String method modifies the byte array. toLowerCase(), replace(), and substring() all return a new String object. The original is unchanged.

Three things depend on this guarantee.

Thread safety. Because a String's contents never change after construction, any number of threads can read the same object without synchronization. This matters for strings used as map keys, class names, file paths, and configuration values, all of which routinely cross thread boundaries.

Hash caching. String has a private int hash field, initially 0. The first call to hashCode() computes the hash from the byte array and stores the result. Every subsequent call returns the cached value. If strings were mutable, the cache would go stale. Because they are not, the cache is always valid, so using strings as HashMap keys is fast.

The string pool. If two objects share the same character sequence and neither can change, they can safely share the same Java object. No caller can tell the difference. That is what the string pool exploits.

The string pool

The JVM maintains a table called the string pool, backed by a hash table of interned string objects. It lives on the heap. Its default size is 65536 buckets and can be tuned with -XX:StringTableSize.

When the JVM loads a class, it encounters string literals in the class's constant pool. For each literal, it looks up the string pool: if the pool holds an entry for that character sequence, the JVM uses the existing object; if not, it adds the new object and returns it. This is why a == b is true above. The class contains two references to the literal "hello", and the JVM resolves both to the same pooled object.

Compile-time constant expressions also land in the pool. The Java compiler evaluates constant folding expressions, concatenations of literals or chains of final string variables, before producing bytecode. The result is treated as a literal.

final String prefix = "hel";
String s = prefix + "lo"; // compile-time constant, interned

Enter fullscreen mode Exit fullscreen mode

But if either variable is not final, concatenation happens at runtime, and the result is not automatically pooled:

String prefix = "hel"; // not final
String s = prefix + "lo"; // runtime result, not in the pool

Enter fullscreen mode Exit fullscreen mode

You can explicitly intern a string with intern(). If the pool holds an equal string, intern() returns that pooled object. If not, it adds the calling string to the pool and returns it.

String a = new String("hello"); // not pooled
String b = "hello"; // pooled literal

System.out.println(a == b); // false
System.out.println(a.intern() == b); // true

Enter fullscreen mode Exit fullscreen mode

In modern Java, calling intern() manually is unusual. The G1 garbage collector can deduplicate string objects automatically at GC time with -XX:+UseStringDeduplication. That approach works without touching each string in code, but it deduplicates objects. It does not change their identity, so == comparisons still differ. The correct way to compare string content in application code is always equals().

Construction methods

Java provides more ways to construct a String than most languages. Each fits a specific scenario.

String literal: "hello"

The most common form. The compiler records the literal in the constant pool; the JVM interns it at class-load time. Use it for any fixed value in source code.

new String(String original)

Creates a new, distinct object from an existing string. The new object is not pooled.

String s = new String("hello"); // new object, not in the pool

Enter fullscreen mode Exit fullscreen mode

This is almost always a mistake. The only historical use, preventing a large backing array from being retained through a substring() reference, no longer applies. Modern JDK substring() does not share storage with the original. Avoid this constructor.

new String(byte[] bytes, Charset charset)

The correct way to decode bytes from an external source, such as a file, a network socket, or a database driver, into a Java string.

byte[] received = inputStream.readNBytes(length);
String message = new String(received, StandardCharsets.UTF_8);

Enter fullscreen mode Exit fullscreen mode

Always specify the charset explicitly. The overload new String(byte[]) uses the platform default charset, which varies by JVM configuration and operating system. Code that depends on the default charset can silently produce different results on different machines.

new String(char[] value)

Creates a string from a char array with a defensive copy. Changes to the array after construction do not affect the string. Use this when you have already built up a char[] and need a String.

String.valueOf(Object obj)

Returns "null" if obj is null, otherwise calls obj.toString(). Use this when you need a string representation of an object that might be null.

String s = String.valueOf(account); // "null" if account is null

Enter fullscreen mode Exit fullscreen mode

The primitive overloads, String.valueOf(int), String.valueOf(long), and String.valueOf(boolean), convert primitives without boxing. They are equivalent to Integer.toString(n), Long.toString(n), and Boolean.toString(b).

String.format() and str.formatted()

Both produce a formatted string using printf-style specifiers: %s for strings, %d for integers, %f for floats, %n for the platform line separator.

String msg = String.format("Account %s, balance %d", id, balance);
String msg2 = "Account %s, balance %d".formatted(id, balance);

Enter fullscreen mode Exit fullscreen mode

formatted() is an instance method added in Java 15. It calls String.format() internally. Use formatted() when the format string is a literal in source code. Use String.format(Locale, format, args) when you need locale-specific number formatting, such as %,d for a thousand-separated integer.

Both involve Formatter parsing overhead on every call. For simple concatenation without alignment or padding, + or StringBuilder is more direct. The next article covers when each is appropriate.

String.join()

Joins strings with a separator without writing a loop.

String csv = String.join(", ", "Alice", "Bob", "Carol");
// "Alice, Bob, Carol"

List<String> ids = List.of("A001", "A002", "A003");
String joined = String.join(", ", ids);

Enter fullscreen mode Exit fullscreen mode

Internally, String.join() delegates to StringJoiner. The next article covers StringJoiner directly.

Text blocks

A text block is a multiline string literal introduced in Java 15 (JEP 378). The opening delimiter is """ followed immediately by a newline. The closing delimiter is """ on its own line.

String json = """
        {
            "id": "A001",
            "balance": 5000
        }
        """;

Enter fullscreen mode Exit fullscreen mode

The JVM strips leading whitespace from each content line. The minimum indentation of all non-empty content lines determines how much. In this example, both the content and the closing """ are indented 8 spaces, so 8 spaces are stripped from every line. Move the closing """ to column 0 to strip no whitespace.

Three escape sequences are specific to text blocks.

A \ at the end of a line suppresses the newline:

String s = """
        Hello \
        World""";
// equivalent to "Hello World"

Enter fullscreen mode Exit fullscreen mode

\s inserts a space and prevents the compiler from stripping trailing whitespace from that position:

String row = """
        Alice \s
        Bob \s
        """;

Enter fullscreen mode Exit fullscreen mode

A text block is a regular String at runtime. It participates in the string pool just like any other literal, and format specifiers work the same way:

String query = """
        SELECT *
        FROM accounts
        WHERE id = '%s'
        """.formatted(accountId);

Enter fullscreen mode Exit fullscreen mode

Text blocks were available as a preview feature in Java 13 and 14; the preview form differs from the final version. Use only the Java 15 form in production code.

Prediction exercise

String a = "java";
String b = "ja" + "va";
String part = "va";
String c = "ja" + part;
String d = new String("java").intern();

System.out.println(a == b);
System.out.println(a == c);
System.out.println(a == d);

Enter fullscreen mode Exit fullscreen mode

Predict each output. Then: how would your answers change if part were declared final?

Top comments (0)