Why is it important for String to be immutable?

Serdar A.
2 min readNov 3, 2024

--

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?

https://storage.googleapis.com/algodailyrandomassets/curriculum/blogs/mutablevsimm.png

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.

--

--

Serdar A.
Serdar A.

Written by Serdar A.

Senior Software Developer & Architect at Havelsan Github: https://github.com/serdaralkancode #Java & #Spring & #BigData & #React & #Microservice

No responses yet