SiteMap  | About    

Why String is immutable in Java ?

The term Mutable means "can change" and Immutable means "cannot change". An Immutable Object means that the state of the Object cannot change after its creation. Here the String is immutable means that you cannot change the object itself, but you can change the reference to the object. Changing an object means to use its methods to change one of its fields or the fields are public (and not final ), so that you can be updated from outside without accessing them via methods. Once string object is created its data or state can't be changed but a new string object is created. An important point to note here is that, while the String object is immutable, its reference variable is not.


Here we see the difference between mutating an object, and changing a reference. str2 still points to the same object as we initially set str1 to point to. Setting str1 to "World!!" only changes the reference, while the String object it originally referred to remains unchanged.


Immutability of strings has positive significance in multithreaded applications because it provides automatic thread safety. Instances of immutable types are inherently thread-safe , because no thread can modify it. Also, String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were S tring not immutable , a connection or file would be changed and lead to serious security threat.


The main drawback of immutable types is that they require more resources than other object types. Because each time it modified, it creates a new one.


The above code segment creates 1000 new string variables. In these type of situations you should use the Java StringBuilder class, which allows you to modify the text without making new String class instances. Java StringBuilder is a Mutable type, that means when you alter it , it still holding same data

Example (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.