Why is string immutable in Java?
I would like to know ,the explanation with an example for this question.
As java uses the concept of string literal strings are said to be immutable.Immutable means unchangeable.Once an object is created in java it's data or state cannot be changed but a new string object is created.Now let us try t understand the concept of immutability by considering an example:
public static void main(String args)
s.concat("working");//concat method appends the string at the end
System.out.println(s);//will print hello because strings are immutable objects.
Consider we have three strings s1, s2 and s3 where s1 and s2 has the same value while s3 has some different value. Since s1 and s2 have same value then only one type of value will be saved. In short string s1 and s2 will point to same location where the value is stored while string s3 will point to some other address where the different value is stored.
Consider we are going to concatenate string s1 so this will create as a separate object in the string, thus this string is called immutable string. So string s1 already had some value let say "one" and it is concatenated by new string and it becomes "one more". It is not replacing the string value in the location provided earlier it just create a new address with the new string.
String s1 will be now separated in terms of pointing to location in the memory, while string s2 will remain pointing to the previous location.
I think string are immutable in java because strings are actually arrays of character and given a specific memory when they are first initialized .So if we change it later it will not be able to hold the new values .If the new values are actually bigger than the original one
Strings are immutable means unmodifiable or unchangeable. Java uses the concept of string literal . If one reference variable changes the value of the object, it will be affected to all the reference variables.