In Java programming language, String is immutable. It means once a String object is created, there is no way to change its value. Any modification on this object leads to create another String object.
If we check the source code of java.lang.String.java:
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
{
/** The value is used for character storage. */
private final char value[];
/* Other code */
/* Other code */
}
It is clear that String object is essentially a char array and modified with final keyword, once value is created, its reference address can not be changed. But the array’s item can be changed directly, for example value[0] = 'd' will modify the first element of this array.
The String class is also modified by final keyword, it means String cannot be inherited.
So why is
Stringobject is immutable?
The key lies in encapsulation and access control:
- The internal array is private. External code cannot directly access or obtain a reference to this array.
- The
Stringclass does not provide anypublicorprotectedmethod that allow us to modify the content of this internal array. - The
Stringclass is declared asfinal. This ensures that no other class can inherit fromStringand add methods to expose or modify thisprivateinternal array.
So String’s immutability is the result of careful design, combining a private internal state, the absence of modification methods, and a final class, all working together to ensure that its instances cannot be changed once created.