Why Strings are immutable in Java?

Why Strings are immutable in Java?

The String is immutable in Java because of its security, thread safety, and memory utilization. Let's go through each reason one by one.

1. Memory space utilization

When we declare a string variable,

image.png

in memory it looks like this,

image.png

The name variable is not the string object per se, but a reference to a String object in memory that it creates with the value "Rick".

When you take another name variable java does not modify the "Rick" object, but rather it creates a new value called "John" in memory and the old reference will now point to the new "John" object.

image.png

image.png

What it means by strings objects are immutable is that String objects in memory are immutable but variables can be changed.

When java creates a string object, it puts objects in the String pool, and every time a new string variable is declared, java will check if the object "Rick" is already present in the pool or not. If it is already present, then the string variable will point to the same "Rick" in the memory rather than creating a different string object "Rick".

image.png

image.png

Since Java does not create different objects for different variables, memory is utilized properly.

Note: If you use the new keyword i.e, String name3 = new String("Rick") then Java will create a string object named "Rick" outside of the previous string pool.

image.png

2. Security

The function func using the variable username has access to the "Rick" variable i.e, it is pointing to the same name "Rick" which is pointed by the name1 variable

image.png

image.png If in case the function func was related to accessing bank details and the String objects were mutable, then we could be able to change the username of that person; which we really don't want to.

With strings being immutable that security issue just vanishes.

3. Thread Safety

If we have 100s of threads, all pointing to the same String object in the memory, even though all the threads are reading it and using it, none of them can change or modify it.

image.png