Skip to content
Go back

Understanding Immutable Strings in Java

Published:  at  09:00 AM

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 String object is immutable?

The key lies in encapsulation and access control:

  1. The internal array is private. External code cannot directly access or obtain a reference to this array.
  2. The String class does not provide any public or protected method that allow us to modify the content of this internal array.
  3. The String class is declared as final. This ensures that no other class can inherit from String and add methods to expose or modify this private internal 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.



Previous Post
Git cherry-pick Command
Next Post
How This Blog was Created