Why is String Immutable and final in Java? It is one of the most important question asked in an Interview with freshers or with the experienced candidates for the Java Developer. Well, as a Java Developer we all know that there might be any application we had ever made without using the String data type. Almost every application uses String in it that too every application creates too many String objects. So, now we will know why the string is designed in such a way in Java implementation classes so that it is immutable and final.
First of all, let us know the String Java Class Implementation:
public final class String implements java.io.Serializable, Comparable<String>, CharSequence { }
What is the word immutable means?
In general english, immutable means unchanging over time or unable to be changed.
What does it means technically that String is immutable?
A below example (Example 1) depicts the statement that the String is immutable in Java.
package Demo; public class StringImmutable { public static void main(String[] args) { String value1 = "EduTechLearners"; //Stored in String Constant Pool String value2 = "EduTechLearners"; //Points to the same storage location in String Constant Pool. //If the String values are same they points to the same storage location System.out.println(value1==value2); //true value2 = value2 + " Learn"; // value2 = EduTechLearners Learn //If the String values aren't same they do not points to the same storage location //Here value1 is different than the value2 System.out.println(value1==value2); //false } }
So, the above class implementation depicts that the String is immutable as Java runtime maintains a “String Constant Pool“. We all know that JVM divides the allocated memory to a Java program into two parts. one is called Stack and another one is called the heap. The stack is used for execution purpose and heap is used for storage purpose. In that heap memory, JVM allocates some memory specially meant for string literals. This part of the heap memory is called String Constant Pool.
Important points to understand String constant Pool :
- Whenever one creates a string object (without using the “new” keyword), the object is stored in String Constant pool and whenever the object is created using the “new” keyword, the string object is stored in heap storage.
- When a string object using String literal is created, JVM first checks the content of the String object. If there exists an object in the String Constant pool with the same content, then it returns the reference of that object. It doesn’t create “new” object. But if the content is different from the existing object then only it creates a new object with the given content.
- There will be no two objects in the String constant pool having the same content. But, there can be two string objects with the same content in the heap memory.
The above Example 1 will be stored in memory as below diagram:
So, the answer to the question is that the String is immutable means that the value of the string is stored only once in a String constant pool i.e. they are never gonna change their values. If the value of the variables is changed, the old value will remain in the String constant pool but the variable is assigned to a new value in the String constant pool. Actually, this is what the string immutable means.
Is new String( ) is also immutable?
The answer to the above question is also “Yes”. The String object created using the “new” keyword are also immutable although they are stored in heap storage memory. A below example proves the same.
package Demo; public class StringImmutable { public static void main(String[] args) { String value1 = new String("EduTechLearners"); //Stored in heap memory area System.out.println(value1); // Prints "EduTechLearners" value1.concat("Learn"); System.out.println(value1); // Prints "EduTechLearners" } }As the value1 is created using the “new” keyword and assigns the value. Now if we tried to concat the string with some additional value, it remains the same as old value. So, it proves that the String object created using “new” keyword are also immutable.
The string is made immutable because of the below reasons:
- Design:- String constant pool can be possible only because String is immutable in Java, this way Java Runtime saves a lot of java 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 other variables also.
- Security:- If String is not immutable then it would cause the severe security threat to the application. For example, database username, password are passed as String to get the database connection and in socket programming host and port, details passed as String. Since String is immutable it’s valued couldn’t be changed otherwise any hacker could change the referenced value to cause security issues in the application.
- Thread Safe:- Since String is immutable, it is safe for multithreading and a single String instance can be shared across different threads. This avoids the use of synchronization for thread safety, Strings are implicitly thread-safe.
- Classloader:- 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 any other class that can do unwanted things to your database.
- Caching:- 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 key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.
Why is String class made final?
String class is FINAL it means that you can’t create any other class to inherit it and can change the basic structure to make the Sting class mutable. That is why the String is made the final class in the Java Implementation.
So, that’s it for now. Hope you understand the concept of why the String is made immutable and Final in the Java Implementation. Please comment below for any further questions.
Read more on Computer Programming articles:-
Contribute to EduTechLearners:-
Please write comments if you want to share more information regarding the above notes. If you want some more notes/books on any of the topics please mail to us or comment below. We will provide you as soon as possible and if you want your’s notes to be published on our site then feel free to contribute on EduTechLearners or email your content to contribute@edutechlearners.com (The contents will be published by your Name).
Explained in a very good way, thanks for efforts.