Why Strings are immutable in Java?
Watch the answer for this Selenium Interview Question in a detailed manner in the below youtube video:
Note: Don’t forget to subscribe to my Youtube channel here: Click here
Notes used for explanation in this Youtube video are provided after the video:
Notes used in the above Youtube Video:
In Java, Strings are by default immutable (i.e. Once created they cannot be changed)
For example: If you assign a value to the String say “Arun Kumar” as shown below:
String name = “Arun Kumar”;
And, in the next statement, I will change the value of the String to other value say “Arun Motoori” as shown below:
name = “Arun Motoori”;
After performing the above two steps, though it looks like the value has been updated. But in reality, a new object will be created to store new value “Arun Motoori” and the old object storing “Arun Kumar” is not deleted. i.e. Instead of updating or changing the value stored in the old object, a new object will be created for every new value assigned to the same variable of String.
So in Strings, on assigning a value to the variable, a new object will be created to store the value and the value stored in the object cannot be changed or mutated. Hence Strings are immutable in Java.
- > For more Selenium Interview Questions and answers, continue to the next post (Click on Next Post link below)
- > Check complete Selenium Interview Questions list here (Click here)
Please leave your questions/comments/feedback below.
Happy Learning ?
On a mission to contribute to the Software Testing Community in all possible ways.