Translate

Tuesday, June 7, 2016

Why String class is immutable in java?



Because of string constant pool. When we create string object by string literal then string object will create in string constant pool and if you create another object by string literal of same content then only reference will get created and that reference point to the older object. So if  we change in one object then changes automatically reflected in another object. That's why string class is immutable in java, means if you change in existing object then new object will get created and the reference start point to the new object.

String s1="hello";

String s2="hello";

System.out.println(s1+" "+s2); // o/p hello hello

s2="bye";

System.out.println(s1+" "+s2); // o/p hello bye




No comments:

Post a Comment