Why String is immutable in java

why string immutable

To make sure that if one reference object is updating the String Object,it should not refelct on others reference objects.

String first ="Test";
String second ="Test";

If String class was not immutable.

If we do operation "first.toLowerCase()" ,Output will be "test".

In this process second value also changes because both first and second was referring to same object "Test",which is not right.

That's why String in java String is immutable so that if one reference object is doing some operation it should not reflect on other object.

Strings are widely used parameter type in java programming.

Be it a loading driver or open a URL connection, we need to pass the information as parameter in form of string.

If string have not been final then someone can change the string value and can breach the security.

Since String objects are immutable, they can be shared between multiple thread,So there is no need to synchronize string operation externally.