Why String is Immutable in Java?Last Updated : 9 Jan 2026 Strings in Java are immutable that means their values cannot be changed once they are created. In this chapter, we will learn why Java strings are immutable and how immutability improves security and performance. Why String is Immutable in Java?Strings are immutable to provide security, memory efficiency, and reliable program behavior. Because strings are widely used to store sensitive information such as passwords, file paths, and URLs, immutability prevents their values from being altered once created. It also allows Java to use the string pool efficiently, where multiple references can safely share the same string object, saving memory. Immutable strings are inherently thread-safe and provide consistent hash values that makes strings dependable when used as keys in collections like HashMap. Understanding String Immutability With ExampleLet's consider the following example to understand the concept of string immutability. Output: Sachin Now it can be understood by the diagram given below. Here Sachin is not changed but a new object is created with Sachin Tendulkar. That is why String is known as immutable. ![]() As you can see in the above figure that two objects are created but s reference variable still refers to "Sachin" not to "Sachin Tendulkar". But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object. For example: Output: Sachin Tendulkar In such a case, s points to the "Sachin Tendulkar". Please notice that still Sachin object is not modified. Why String Objects are Immutable in Java?Java uses the concept of string literals, where multiple reference variables can point to the same string object stored in the string pool. For example, if several reference variables refer to the same string value "Sachin", and that string were mutable, a change made through one reference would affect all others. This could lead to unexpected behavior in programs. To prevent such issues and ensure safe and predictable behavior, String objects are immutable in Java. The following features of the String class contribute to its immutability:
Next TopicString Comparison in java |
We request you to subscribe our newsletter for upcoming updates.