Immutable meaning : cannot be changed.
JVM allocates the memory into parts, one
is stack (for execution purpose) and the other is heap (for stoning
objects). And in heap JVM allocates some
memory especially for string literals called as String constant pool.
String objects are cached in string pool. And these
objects are shared between multiple clients. So there is a risk of operations
made by one client effects the other clients too.
Reasons:
For security:
in the sense we pass the hostname, password as string as parameters.
There is chance of changing these values if string is mutable.
Explanation:
When a string is created, an object is created
inside heap memory as a string pool.
Ex: string s1=”hello”;
If we create another string s2=”hello”, s2 is referenced to value s1 is referencing,
but when we change the value of s2 a new object is created and s2 is referenced
to that, this happens because string is immutable, if string is not immutable
then change s2 will also change the value of s1 which is not desired.
