Java String: Immutability and Memory Behavior
Understand Java String immutability, the string pool, and how to handle concatenation and memory efficiently in practical code.

The Java String class is one of the most used types in the language, yet its immutability and memory behavior often surprise developers who come from mutable string types in other languages. In Java, a String object is immutable: once created, its character sequence cannot change. Any operation that changes the visible text returns a new String object and leaves the original unchanged. This design has deep implications for memory usage, equality checks, and performance in real applications.
What Makes Java String Immutable
Older JDKs stored a String's characters in a private final char[] array; modern JDKs use a private final byte[] array with a coder flag, which is what makes compact strings possible. There are no public methods that mutate that array. Methods like toUpperCase(), replace(), or substring() return a string containing the modified content; they never mutate the original. This immutability is not accidental; it enables safe sharing, caching, and thread safety without synchronization.
For example:
String original = "hello";
String upper = original.toUpperCase();
System.out.println(original); // hello
System.out.println(upper); // HELLOThe original string remains unchanged. If you need a mutable character sequence, you must use StringBuilder or StringBuffer explicitly.
The String Pool and Interning
Because strings are immutable, the JVM can safely cache them in a string pool. When you write a string literal, the compiler places it in the class file constant pool, and the JVM interns it at runtime, reusing one instance for identical literals. This reduces memory for repeated constants.
String a = "hello";
String b = "hello";
System.out.println(a == b); // true, same reference from the poolHowever, strings created with new String("hello") are not automatically interned. They are separate objects on the heap, even though their content is identical:
String c = new String("hello");
System.out.println(a == c); // false
System.out.println(a.equals(c)); // trueYou can explicitly intern a string using intern(), but doing so too aggressively can cause performance issues in the pool's hash table. The pool is implemented as a hash table, and overuse can lead to contention in multithreaded environments.
How String Concatenation Works
Concatenating strings with the + operator is convenient, but the generated code depends on the JDK. A constant expression such as "foo" + "bar" + "baz" is folded into a single string at compile time. For variable concatenation, older javac versions generate code similar to a single StringBuilder chain, while JDK 9 and later use an invokedynamic-based string-concatenation factory. A few concatenations are inexpensive either way.
The real problem is repeated concatenation inside a loop, which allocates many intermediate objects:
String result = "";
for (int i = 0; i < 1000; i++) {
result += i; // Allocates many intermediate objects on each iteration
}This loop creates many temporary objects. The fix is to use a single StringBuilder outside the loop.
When to Use StringBuilder
Use StringBuilder when you need to build a string incrementally, especially in loops or when the number of parts is unknown at compile time. StringBuilder maintains a mutable buffer and only produces a String when you call toString().
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i);
}
String result = sb.toString();This avoids the repeated allocation of intermediate strings. StringBuffer is the thread-safe counterpart, but its synchronization overhead is rarely needed because building a string is usually local to a method. Prefer StringBuilder unless you are sharing the buffer across threads.
Comparing Strings Correctly
A common mistake is using == to compare strings. Since == compares references, it only works when both operands are interned or refer to the same object. For content equality, always use equals().
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // trueFor case-insensitive comparison, use equalsIgnoreCase(). For membership checks or deduplication, a HashSet or HashMap can avoid many equals calls, but individual content comparisons should still use equals(); never rely on == for content.
Performance and Memory Considerations
The immutability of String means that every modification creates a new object. This affects memory footprint and garbage collection pressure. Large strings that are modified frequently can cause significant overhead. In such cases, StringBuilder is the appropriate tool.
Another nuance is the substring() method. In older JDKs (before Java 7u6), substring() shared the underlying char[] with the original string, which could lead to memory retention if you kept a small substring of a large string. Modern JDKs generally copy the characters, which avoids the leak but increases allocation. This is a tradeoff worth knowing when processing large text.
Also, in HotSpot the string pool is a hash table with a default of 60013 buckets in recent JDKs. If you intern too many distinct strings, the pool can degrade into a linked list, slowing down intern() calls. In most applications, you do not need to call intern() manually; rely on the compiler's literal pooling and use equals() for comparison.
Handling Large Strings and Memory Footprint
When dealing with very large strings, such as reading a whole file into memory, be aware that the JVM stores characters as UTF-16 internally, or as one byte per character when compact strings are enabled and the content fits in Latin-1. A one-million-character string can occupy roughly one or two megabytes, plus object overhead, depending on the content. If you need to process large text, consider streaming it with a Reader or using StringBuilder to build the result incrementally, rather than holding multiple copies.
For example, reading a file line by line and accumulating into a StringBuilder is more memory-efficient than reading the entire file into a single String and then splitting it:
StringBuilder content = new StringBuilder();
try (BufferedReader reader = Files.newBufferedReader(Paths.get("data.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append('\n');
}
}
String result = content.toString();This approach avoids creating multiple large intermediate strings. If you need to manipulate substrings of a huge text, consider using CharSequence views or custom data structures rather than repeatedly calling substring().
Understanding String immutability and its memory behavior is essential for writing efficient Java code. By choosing the right construction method and comparison strategy, you can avoid common performance pitfalls and keep your applications responsive.
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.