Tutorial

Why String is Immutable in Java?

Published on August 3, 2022
author

Pankaj

Why String is Immutable in Java?

Why String is immutable in Java is one of the popular interview questions. The string is one of the most used classes in any programming language. We know that String is immutable and final in Java. Java runtime maintains a String pool that makes it a special class.

Why String is immutable in Java?

why string is immutable in Java, why string is immutable and final in java Let’s look at some of the benefits of String immutability, that will help in understanding why String is immutable in Java.

  1. String pool is possible only because String is immutable in Java. This way Java Runtime saves a lot of heap space because different String variables can refer to the same String variable in the pool. If String would not have been immutable, then String interning would not have been possible because if any variable would have changed the value, it would have been reflected in the other variables too.
  2. If String is not immutable then it would cause a severe security threat to the application. For example, database username, password are passed as String to get database connection and in socket programming host and port details passed as String. Since String is immutable, its value can’t be changed otherwise any hacker could change the referenced value to cause security issues in the application.
  3. Since String is immutable, it is safe for multithreading. A single String instance can be shared across different threads. This avoids the use of synchronization for thread safety. Strings are implicitly thread-safe.
  4. Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader. For example, think of an instance where you are trying to load java.sql.Connection class but the referenced value is changed to myhacked.Connection class that can do unwanted things to your database.
  5. Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for the key in a Map and its processing is faster than other HashMap key objects. This is why String is the most widely used as HashMap keys.

Above are some of the reasons I could think of that shows benefits of String immutability. It’s a great feature of the Java String class and makes it special. Read this post to know how to write your own immutable class.

You can checkout more Java String examples from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 11, 2013

Whats the use intern() method in String class? String s1=“Hello”; String s2=new String(“Hello”); System.out.println(s1==s2); // this is shows output false s2=s1.intern(); System.out.println(s1==s2); // this gives output true, Can u explain how it works?

- siddu

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 11, 2013

intern() method looks for the String in the pool and if found, returns the reference. Thats why after calling intern() both string variables are referencing to same variable and output is TRUE.

- Pankaj

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 17, 2015

Hi, actually I’am a littel bit confused … I think in this code the use of intern() is not necessary we can use s2=s1 and it will give us true as a result because here s1 and s2 variables will be referencing to the same variable. Yes intern() method looks for the String in the pool and if it is found, it returns the reference, so if we really want to produce this behave we should write s2=s2.intern()

- Ameni

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
November 20, 2017

When the intern() method is invoked on a String object it looks the string contained by this String object in the pool, if the string is found there then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

- Yogesh

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    October 15, 2014

    String str=new String(“Hello”); How many objects are created in this case ? String “Hello” passed as argument where is it stored ?

    - Arunda

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 3, 2014

    Hi Pankaj, Would appreciate if you please answer the above question of Arunda.

    - Abhi

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 3, 2014

    Sorry for late response. 2 String objects will be created. First “Hello” string in the pool because we are passing string literal as argument. Second one in the heap.

    - Pankaj

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 3, 2014

    That clears the doubt. Thank you Pankaj. One more question, does GC has to do anything with String Pool. Does it has some different approach towards String pool than string objects stored on Heap.

    - Abhi

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      January 8, 2016

      2 object are created

      - Siddharth Gelda

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        January 16, 2015

        String s1 = “ABC”;-- This goes to pool directly String s2 = new String(“ABC”);–according to ur one of answers above , this created 2 objects, 1 in pool and another in heap memory. I am little confused. So when we check as below s1==s2, then it gives false as s2 refrers to heap area. so, what happens to the reference to the pool area as object is created there also.

        - Ankush Raina

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        March 2, 2017

        Hi Pankaj, Would appreciate if you please answer the above question of Ankush Raina.

        - Sachin

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 1, 2017

        String s2 = new String(“ABC”) won’t create another object in pool area as already “ABC” is available in pool area. Object created in heap area may be destroyed by Garbage Collector but “ABC” created in pool area will be available through out the program for reuse.

        - Lorina

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 7, 2018

        Java 7 onwards string pool has been moved to heap area and will be available for GC

        - Pankaj Chauhan

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          August 18, 2017

          Hi Pankaj, One query based on String immutability feature ,what is better to store a password charArray or String ?

          - Sonam Devikar

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          March 5, 2018

          Hi Pankaj, When does string caches it’s hashcode? I found this is article saying, string caches it’s hashcode during when we create a string literal. if this is true , then why when we create string object, it’s “hash” is showing 0 ? I think Once after the hashcode() method get called, the hashcode getting cached to the object header. So can anybody clear my confusion ? String hashcode is computed and getting cached during the object creation time or once the hashcode() get computed then only it’s getting cached in the string object.

          - Abhi

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            August 8, 2018

            Hi there, String data type is not a good option to hold password information in the application. Since String is immutable in nature and there is no any way to change its value ( apart from Java reflection ). So you can not erase or override its contents and it will be saved in “String pool” and if anyone gets the memory dump then password might get exposed. It could lead to a security breach. Instead of String, We can use the char array as you can easily erase or overwrite its contents after use.

            - Kiran Pophaler

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              February 7, 2018

              Hi Pankaj, You mentioned that String is immutable because the hashcides are cached during creation. I didn’t get the meaning of it. Could you please explain?

              - Sudha

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              February 8, 2018

              You got it other way around. String hashcode is cached because String is immutable and it’s a huge performance benefit for using in collection classes, specially HashMap key. Read more at Java HashMap.

              - Pankaj

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                July 10, 2018

                Thats a great point about a `String` object being an excellent key for `HashMap`s. Had never thought about that before…

                - Akshayraj A Kore

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  January 27, 2019

                  I have one question ad String used for security purpose so none can modify secure data…But my question is if we assign new value in already created String then older secured data does not have any reference…Because that occupied by new string…Then how is it secure?

                  - Santosh Gupta

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  January 30, 2019

                  You are technically not assigning a new value to already created string, rather you are creating/using a different string from the pool of strings. What I mean to say is: Suppose String username=“xyz” now if you modify username to username=“abc” then “abc” if it exists in the pool of strings its reference would be returned and thus “xyz” as a value is not modified and thus is immutable. From the security aspect, if the string was mutable and we had changed username’s value in the memory location, then that would have been a security threat. In this case, its simply trying to log in with the wrong Username and thus not being able to log in.

                  - Tanmoy Ghosh

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    December 19, 2019

                    Actually what happen when you are doing s1 = new String(“Nilakshi”); then two obj is created.one in heap and another one is in constant pool .Like the obj which is created by new keyword is point and have ref of the string constant pool obj Nilakshi. And when you doing s1= “Hashada” the instead of pointing the heap obj it point scp obj harshda. So that now s1 and s2 have same ref which is in scp (“Harshda”).

                    - Rohit

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      April 3, 2019

                      String s1=”Hello”; String s2=new String(“Hello”); System.out.println(s1==s2); Will above two strings will be true post Java 7, as string pool moved to Heap area ?

                      - Rohit

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      May 6, 2019

                      No

                      - Ashok

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        September 13, 2019

                        No. Because String s1 is referring to String present in StringPool as it created using String literal. On the other hand, String s2 is created using new operator, so it is created seperately. So, Both s1 and s2 are referring to different strings.

                        - Nilakshi Patil

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          September 13, 2019

                          Refer the below code : public class StringImmutable_Test_1_0 { public static void main(String args[]){ String s1 = new String(“nilakshi”); String s2 = “harshada”; String s3 = “nilakshi”; s1 = “harshada”; if(s1 == s2) System.out.println(“s1 and s2 has same reference”); else System.out.println(“s1 and s2 doesn’t have same reference”); s1 = new String(“nilakshi”); if(s1 == s3) System.out.println(“s1 and s3 has same reference”); else System.out.println(“s1 and s3 doesn’t have same reference”); } } This gives me output as follows --> s1 and s2 has same reference s1 and s3 doesn’t have same reference Why this is giving me such result although string is immutable ?

                          - Nilakshi Patil

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          September 13, 2019

                          String immutability has nothing to do with the object reference that is checked in == operator. Please read What is Java String Pool?

                          - Pankaj

                            Try DigitalOcean for free

                            Click below to sign up and get $200 of credit to try our products over 60 days!

                            Sign up

                            Join the Tech Talk
                            Success! Thank you! Please check your email for further details.

                            Please complete your information!

                            Become a contributor for community

                            Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                            DigitalOcean Documentation

                            Full documentation for every DigitalOcean product.

                            Resources for startups and SMBs

                            The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                            Get our newsletter

                            Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                            New accounts only. By submitting your email you agree to our Privacy Policy

                            The developer cloud

                            Scale up as you grow — whether you're running one virtual machine or ten thousand.

                            Get started for free

                            Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                            *This promotional offer applies to new accounts only.