Wednesday, 22 March 2017


How Strings are Immutable?

Let's Understand this with an Example.

Example:

String s1="abc";
String s2="abc";

s1="bcd";

System.out.print(s1);
System.out.print(s2);

/*Both Strings were referring to same object so if the reference variable
is changed then it should also change the String "s2". So let's take a look at the Output. */

Output:
bcd
abc


Explanation
So from the Above Example can we say that String are not Immutable? Well on the Outside it looks like the String is actually changed. But on the Inside, A Object is being Created(for "bcd") and s1 is assigned to it. Now both s1 and s2 are referring to different objects.

1 comment: