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.
Let’s look at some of the benefits of String immutability, that will help in understanding why String is immutable in Java.
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.
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.
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.
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.
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.
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.
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 ?
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 ?
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?
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?
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.
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?
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
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
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
Thats a great point about a `String` object being an excellent key for `HashMap`s. Had never thought about that before…
- Akshayraj A Kore
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
Hi Pankaj, One query based on String immutability feature ,what is better to store a password charArray or String ?
- Sonam Devikar
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
String str=new String(“Hello”); How many objects are created in this case ? String “Hello” passed as argument where is it stored ?
- Arunda
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