Strings are Immutable

No matter whatever you do, you cannot destroy a String, unless and until JVM is recycled.
Yeah, it's sad but true !!

Java has designed Strings in such a way that Strings are immutable. So, keep in mind that whenever we do operations on a String, it actually creates a new instance of a String & assign the new value into it.











public class ImmutableString {

 public static void main(String[] args) {
  String a = "Test";
  String b = a;
  System.out.println(a==b);
  a= a+"";
  System.out.println(a==b);;
 }
}
The Output is :

true
false

So, we can see that after adding a blank string to the string 'a' the object has been changed. That means that the old String is abadoned now & a new string object is created & the value is now assigned to it.


Happy Learning !!

No comments :

Post a Comment