Why Is Java’s String Immutable? Uncover the JVM’s Secret
This article explains why Java String objects are immutable, how the JVM’s string constant pool reuses instances, the role of the final keyword and char[] storage, and demonstrates that all mutating operations actually create new String objects rather than altering the original.
Is String immutable?
Assigning a new literal to a String variable does not modify the original object; the variable simply starts referencing a different String instance.
public class App {
public static void main(String[] args) {
String a = "111";
a = "222";
System.out.println(a);
}
}The JVM maintains a String constant pool . When a literal is created, the pool is checked first; if the value already exists, the same instance is returned, otherwise a new object is allocated and placed in the pool.
String objects are immutable because the class is declared final and stores its characters in a private final char[] value. Neither the class nor the underlying array can be altered after construction.
public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
private final char[] value;
// constructors and methods omitted for brevity
}All mutating methods such as concat, replace, substring, and trim create a new String object instead of changing the original.
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) return this;
int len = value.length;
char[] buf = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}Code examples also show the difference between reference equality ( ==) and content equality ( equals):
String a = "111";
String a1 = "111"; // same pool instance
String b = new String("111"); // distinct object
System.out.println(a == a1); // true
System.out.println(a.equals(a1)); // true
System.out.println(a == b); // false
System.out.println(a.equals(b)); // trueThese demonstrations confirm that once a String object is created it never changes; any operation that appears to modify it actually produces a new object, while the constant pool may share identical literals to save memory.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
