0% completed
Strings, the String Pool, and Immutability
On This Page
Why is String immutable in Java?
What is the string pool, and what does new String() do?
How is a String stored in memory?
Why is char[] sometimes preferred over String for a password?
Predict the Output
Key Takeaways
A String object never changes its text after it is created. Methods that appear to change it, such as toUpperCase() and replace(), return a string with the result and leave the original as it was. Several surprising properties of strings follow from this decision: the sharing of literals, the results of ==, and the advice about passwords.
The questions below start from that one property and explain why it was chosen, how it allows literals to share objects, how the text is stored in bytes, and when an unchangeable object is a disadvantage.
Why is String immutable in Java?
Level: Junior
A String is immutable, which means that its text cannot change after creation, so that one object can be shared safely by any code. The same decision also makes the hash code cacheable, keeps map keys valid, and makes strings safe to use from several threads.
Three parts of the class enforce it. The class is final, so no subclass can replace its methods. The text is in a private final array, so other classes cannot read or write it directly. Finally, no method of the class writes to that array after construction.
Each benefit removes a specific problem:
| Benefit | What could go wrong with mutable strings |
|---|---|
| Sharing | A change through one variable would change the text in every other place that uses the object |
| Cached hash code | The saved value would be wrong after a change |
| Safe map keys | A changed key would be in the wrong bucket and could not be found |
| Thread safety | Two threads would need a lock to read and change the same text |
| Security | A file name could be changed after a permission check and before the file is opened |
The program below calls methods on a string and then compares references with ==.
mango MANGO, and still mango true true false
The first call to toUpperCase() has no visible effect, because its result is not used. The next two comparisons are true: concat("") and substring(0) have nothing to change, so they return the same object. Returning it is safe because nobody can modify it. The last call has a different result, so it returns another object.
Common mistake: Calling name.trim() or name.replace(...) as a statement and expecting name to change. The result must be assigned, as in name = name.trim().
Follow-up questions
1. If strings are immutable, why can a String variable show different text later?
The variable can receive a reference to a different object, while each object keeps its text. The statement name = name.trim() changes the variable only. A final variable cannot be reassigned, and that restriction is separate from the immutability of the object.
2. Why is the class String declared final?
A subclass could override methods such as length() and charAt() and return different results over time. Code that received such an object as a String could no longer rely on immutability. A permission check, for example, could see one file name, and the code that opens the file could see another.
What is the string pool, and what does new String() do?
Level: Junior
The string pool is a set of unique strings that the JVM keeps, and equal string literals refer to the same object in it. The expression new String("apple") always creates another object outside the pool. That object is equal to the literal, and it is not the same object.
A string literal is text in double quotes in the source code. The language guarantees that equal literals refer to one object, even when they appear in different classes. Adding a string to the pool, or finding the equal string that is already there, is called interning.
Three rules decide which object an expression returns:
- A literal or a constant expression is interned. A constant expression consists of literals, constants, and operators, such as
"man" + "go". The compiler computes its value. - A string that is computed while the program runs is usually a separate object. This includes the result of
new String(), of reading input, and of+with a variable that is not constant. - The method
intern()returns the string from the pool. If no equal string is there, it adds the current one first.
a == b: true a == c: false a == d: true c == d: false a.equals(c): true
The variables a and b hold the literal "apple", c holds new String("apple"), and d holds c.intern(). Only c refers to a separate object, so both == comparisons with c are false.
Notice that both objects hold the text apple. That is why equals() returns true for every pair, and why it is the right comparison for text.
Common mistake: Comparing strings with == because a test with literals returned true. Text that comes from a user, a file, or a database is usually a separate object, and the comparison then returns false.
Follow-up questions
1. How many objects can new String("apple") create?
It creates one or two String objects. The new expression always creates one. The literal adds another object to the pool if no equal string is there yet. In the JDK 21 source, the two objects share the same array of bytes, because the constructor copies only the reference to it.
2. When is it useful to call intern()?
It can save memory when a program keeps many equal strings that it reads at run time. Suppose 1,000,000 orders are loaded from a file, and each has a status such as "SHIPPED". Interning the status keeps one object for each different text. Every call costs a search in the pool, and an enum is often the better type for a small fixed set.
How is a String stored in memory?
Level: Mid-level
Since Java 9, a String stores its text in an array of bytes, with one byte for each char if all of them fit and two bytes otherwise. This design is called compact strings. A second field, named coder, records which of the two formats is used.
The one-byte format is Latin-1, which covers the character codes 0 to 255. The two-byte format is UTF-16, in which a char is one unit of 16 bits. A single character outside Latin-1, such as the euro sign, moves the whole string to the two-byte format.
Some characters, including most emoji, do not fit in 16 bits. Unicode gives every character a number, called a code point, and a code point above 65,535 is stored as two char values, called a surrogate pair. The method length() counts char values, so such an emoji has length 2.
The program below applies the storage rule to three strings. It computes the stored bytes, because the private array cannot be read directly.
mango: length 5, code points 5, stored bytes 5, UTF-8 bytes 5 mango and euro sign: length 6, code points 6, stored bytes 12, UTF-8 bytes 8 emoji: length 2, code points 1, stored bytes 4, UTF-8 bytes 4 first char is half of a pair: true
Adding one euro sign raises the stored size from 5 to 12 bytes, because all six characters now take two bytes. UTF-8 is a different format, which is used in files and on networks, so its count can differ from the stored bytes. In the last line, charAt(0) returns half of the emoji.
Look at the bytes of the letters in the lower row, which are written as hexadecimal numbers. Each letter gains a byte with the value 0 when the string uses UTF-16, although the letters themselves did not change. The picture writes the higher byte first, while the order in memory depends on the processor.
Common mistake: Using length() as the number of visible characters, or as the number of bytes in a file. The first differs for many emoji, and the second depends on the encoding that is used to write the text.
Follow-up questions
1. How do you process text that can contain emoji, one character at a time?
<details><summary>Show answer</summary>Use codePoints(), which returns whole code points instead of char values. A loop with charAt() would return the two halves of a surrogate pair separately. A code point is still not always one visible symbol, because some symbols combine several code points. For those, the class BreakIterator finds the boundaries, and since Java 20 it also keeps combined emoji together.
2. Do compact strings make charAt() slower than constant time?
No, charAt(i) still takes constant time. All characters of one string use the same width, so the position in the byte array is i or 2 * i. The method reads coder first to choose between the two. This is an advantage over UTF-8, where characters have different widths and the position of character i is not known directly.
Why is char[] sometimes preferred over String for a password?
Level: Mid-level
The characters of a char[] can be overwritten as soon as the password has been used, while the text of a String cannot. A String remains in memory until the garbage collector reclaims it, and the program does not control when that happens. A heap dump, which is a file with the objects in memory, can contain the text during that time.
The JDK follows this idea. The method Console.readPassword() returns a char[], and PBEKeySpec, a class used to derive encryption keys, accepts a password as a char[].
matches: true array: ****** string: mango7
The comparison uses Arrays.equals(), because equals() on arrays compares references. After Arrays.fill(), the characters are no longer in the array. The call to replace() created another string, and the original text is unchanged.
The advantage has three limits:
- A password often arrives as a
Stringalready, for example from a web framework, and the array is then an additional copy. - A garbage collector that moves objects can leave an earlier copy of the array in memory.
- Overwriting only shortens the time during which the password can be read. It does not replace encrypted connections and stored password hashes.
Common mistake: Converting the array to a String in order to compare it or log it. The conversion creates exactly the object that the array was meant to avoid.
Follow-up questions
1. Does a String password stay in memory until the program ends?
Not necessarily, because an unused string can be reclaimed by the garbage collector. The time is unknown, and the old bytes can remain until the memory is used again. A password that is written as a literal in the source code is worse. It can stay in the pool as long as its class is loaded, and anyone who has the class file can read it.
</details>2. Is a password in a char[] protected from being printed by accident?
Not always, because System.out.println(array) with a char[] prints the characters. The class PrintStream has a println method for exactly this type. In a string concatenation, the array is converted with Object.toString(), which gives the type and a hash value. A password should never reach a logging call.
Predict the Output
Both start and end are final, but they are initialized in different ways. Decide what each of the five comparisons prints.
The program prints true, false, true, false, and true. A final variable that is initialized with a constant expression is a constant. The expression start + "go" is therefore constant, and the compiler stores the literal "mango". The variable end is final but not a constant, because it is initialized with a new expression. The text of start + end is computed at run time. intern() finds the equal string in the pool, which is the object that whole refers to. The call to substring() also creates its result at run time. The last line compares the text.
Key Takeaways
- A
Stringcannot change after creation, so it can be shared, used as a key, and read by several threads. - Equal literals and constant expressions refer to one object in the string pool, and
new String()always creates another object. ==on strings compares references, so compare text withequals().- Since Java 9, text is stored in bytes: one byte for each
charin Latin-1, or two in UTF-16 for the whole string. length()countscharvalues, and one emoji usually takes two of them.- A
char[]can be overwritten after use, which shortens the time that a password is readable in memory.
Because each change produces another string, building a long text from many parts can create many objects. The lesson StringBuilder, StringBuffer, and Concatenation counts the characters that are copied and shows the alternative.
Reading Progress
0%
On This Page
Why is String immutable in Java?
What is the string pool, and what does new String() do?
How is a String stored in memory?
Why is char[] sometimes preferred over String for a password?
Predict the Output
Key Takeaways