Why Strings are Immutable in Java?

This is no doubt, most asked beginner level java interview question. And sometimes you can face at medium level interviews also. So, my suggestion is to learn it here and for ever.

Lets start with immutability itself. An immutable object is an object which state is guaranteed to stay identical over its entire lifetime. This is really a good definition. Isn’t it? It means that the state of object once initialized, can never be changed anyhow.

Normally immutability in java is achieved through following steps :

  1. Don’t provide mutator methods for any field
  2. Make all fields final and private
  3. Don’t allow subclasses by declaring the class final itself
  4. Return deep cloned objects with copied content for all mutable fields in class
Please note that while it is possible to implement immutability without "final" keyword, its use 
makes that purpose explicit, to the human (the software developer) and the machine (the compiler).

Java also has its share of immutable classes which are primarily String class and wrapper classes. In this post, we will understand the need of immutability for String class.

1) Security : The first and undeniably most important reason is security. Well, its not only about your application, but even for JDK itself. Java class loading mechanism works on class names passed as parameters, then these classes are searched in class path. Imagine for a minute, Strings were mutable, then anybody could have injected its own class-loading mechanism with very little effort and destroyed or hacked in any application in a minute.
[ Well, I think in this case java didn’t have got any popularity today… 🙂 and nobody would be using it]. It means Strings were immutable that’s why java is still around in the game.

2) Performance : I believe that it is not the immutability of String class that gives it performance, rather it is string pool which works silently behind the scene. But at the same time, string pool is not a possibility without making String class immutable. So, it all again comes down to immutability of String class which allowed string pools, and thus better performance.

3) Thread safety: Immutable objects are safe when shared between multiple threads in multi-threaded applications. Just understand and learn it. There is no super logic. If something can’t be changed, then even thread can not change it.

As String class is main building block of java programming language, because of its use in class loading mechanism, it was indeed a must use case to prevent the String class from being dirty in case of multiple thread. Immutability does the magic here.

I think its enough reasoning to satisfy the need of interviewer. If after these explanations he is not satisfied, he never will be.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

17 thoughts on “Why Strings are Immutable in Java?”

  1. If String is immutable, then why its content can be modified ?

     
    public static void main (String[] args) {
    String st1= "hello";
    s1=s1+" India";
    } 
    
    Reply
  2. Hi Lokesh,
    I have 1 query to ask, please help me out:

    Is there any way to find out, how many objects would create in my java program. For e.g

    String str= “abc”+”xyz”;

    Reply
  3. Hi, I didn’t understand this statement in above explainations about hacking , “Imagine for a minute, Strings were mutable, then anybody could have injected its own class-loading mechanism with very little effort and destroyed or hacked in any application in a minute” Also ” string pool is not a possibility without making String class immutable” please elaborate little more details on this discussions

    Reply
    • OK. So i got two things to explain. Lets make it clear one by one.

      1) We know in java load classes using Class.forName(string). If Strings were mutable, then someone wrote the code to load “java.io.Writer”. This string variable will be in pool. Now, some evil code can access this pool and change the string to “com.MakeHavocWriter” and now when code gets executed, one can easily imagine the consequences.

      2) String pool is there so that one String instance can be referred from multiple reference variables. If string is mutable, then one object can change the string content and other will see this undesired value.

      See the fact is that String pool was designed for sake of performance, by minimizing the total count of string instances (not references) in application memory space. And as in above scenario, if pool makes the string values changing undesirably, then no one will prefer to use it.

      Reply
      • security is not so obvious , it is mainly for performance, and thread safety i would say/

        about security , usually we done want to hack “Oracle java base class” but applicative class
        And there if you have a jar with for instance Checkpassword.class can can use decompile it, look on the signature, and change the checkPass() to return true, and wrap it to the jar (as very few jar are signed) and run the application with it. so that you “hack” some how the class loader. and job is done.

        as a benefits to immutability and about performace
        the hashcode of a string is computed only once (the first time you call hashcode()) , that is a great point about perf ,( string is very often use in hashmap.)

        Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.