cover-img

Why Strings are immutable in Java?

19 June, 2022

19

19

1

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,
in memory, it looks like this,
img
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.
img
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".
img
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.
img
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
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.
img
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.
img

java

blog

19

19

1

java

blog

Shashank Bhat G S
Intern @Sahaj Software | Prev CCO @ Showwcase | Web-developer | Blogger

More Articles