When interviewed, I was questioned as to why String is immutable.
I responded as follows:
A string pool object will be formed in Java when a string like String s1="hello" is produced, and s1 will point to hello.
Now, if we execute String s2="hello" again, no new object will be created; instead, s2 will point to hello since JVM will first determine whether or not the identical object is already there in the string pool.
Only a new one is created if none already exists.
Now, if Java were to permit string mutability, changing the value of s1 to "hello world" would likewise alter the value of s2 to "hello world," proving that java strings are immutable.
Would someone kindly let me know if my response is correct?