Hi everyone;
String is immutable.
Some interview questions about immutable of string was asked by interviewer to candidates.
Why is it important for String to be immutable?
1) Advantages of String pooling
String Pool is a special storage area in the Java heap. When you create a new string literal from the String class, the JVM will first check if the string already exists in the string pool. If it does, the JVM will return a reference to the existing string object rather than creating a new object. This result in more free space in heap size.
2) Class Loaders
Java ClassLoaders use String. Because of not changing its value, Java ClassLoader loads right class.
3) Allow sharing of variables in Multi-threading
String is safe because it is immutable. A String instance is shared by many different threads. (thread-safe)
4) Caching
Hashcode is String. Hashcode remains the same.Because String doesn’t change. In this way KEYs of Map don’t change.For example in a hashmap. being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes.
5) For Security
Network connections, database url, username,password etc. all of them is String. If String was not immutable, hackers would change its value.
I hope it was useful for you.
Thanx for reading.