HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / String / Why Strings are Immutable in Java?

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?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. yash

    December 19, 2018

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

     
    public static void main (String[] args) {
    String st1= "hello";
    s1=s1+" India";
    } 
    
    • Lokesh Gupta

      December 19, 2018

      The content is not modified. A new string object is created everytime.

  2. Puneet Saneja

    January 7, 2016

    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”;

    • Lokesh Gupta

      January 8, 2016

      You can get idea from https://docs.oracle.com/javase/6/docs/technotes/tools/share/jvisualvm.html

  3. Sumit

    February 11, 2015

    If string is immutable then how can we create its object using new ,i.e, String a= new String (“Test”);

    • Lokesh Gupta

      February 11, 2015

      Perhaps you are confusing with singleton and immutability. Singleton prevents instance creation (allows only one). But immutability does not prevent creating new instances, it just prevents the state of instance once it is fully created.

      • Sumit

        February 11, 2015

        Thanks for the prompt response…
        i got your point but string is both singleton and immutable and as i know we cannot create instance of a singleton class using new operator but in case of string we can, so i am bit confused .Please help!!!

        • Lokesh Gupta

          February 11, 2015

          Where you read that String class is singleton. It’s incorrect.

        • Thiyagarajan

          November 20, 2015

          String is not a singleton. Its immutable only.

  4. shekhar

    September 19, 2014

    could not understand about class loading , how does it break ?

  5. sagar

    November 19, 2013

    can u post something on class loading architecture and the diff types of loaders.

  6. ankit sharma

    October 25, 2013

    hey i’m freeshar i want know about java and future in java

    • Lokesh Gupta

      October 25, 2013

      You will be secured for your lifetime if you managed to be a good programmer.

  7. Anant

    August 12, 2013

    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

    • Lokesh Gupta

      August 12, 2013

      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.

      • Francois

        August 23, 2013

        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.)

        • H Singh

          October 14, 2013

          Hi Francois,

          Can you please elaborate the last para from your reply.

          Thanks.

Comments are closed on this article!

Search Tutorials

String methods

  • String concat()
  • String hashCode()
  • String contains()
  • String compareTo()
  • String compareToIgnoreCase()
  • String equals()
  • String equalsIgnoreCase()
  • String charAt()
  • String indexOf()
  • String lastIndexOf()
  • String intern()
  • String split()
  • String replace()
  • String replaceFirst()
  • String replaceAll()
  • String substring()
  • String startsWith()
  • String endsWith()
  • String toUpperCase()
  • String toLowerCase()

String examples

  • Convert String to int
  • Convert int to String
  • Convert String to long
  • Convert long to String
  • Convert CSV String to List
  • Java StackTrace to String
  • Convert float to String
  • String – Alignment
  • String – Immutable
  • String – StringJoiner
  • Java – Split string
  • String – Escape HTML
  • String – Unescape HTML
  • String – Convert to title case
  • String – Find duplicate words
  • String – Left pad a string
  • String – Right pad a string
  • String – Reverse recursively
  • String – Leading whitespaces
  • String – Trailing whitespaces
  • String – Remove whitespaces
  • String – Reverse words
  • String – Find duplicate characters
  • String – Check empty string
  • String – Get first 4 characters
  • String – Get last 4 characters
  • String – (123) 456-6789 pattern
  • String – Interview Questions

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)