Saturday, December 29, 2012

Why String is immutable or final in Java

1.
String A = "Test"
String B = "Test"
Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.
2.
In case if String is not immutable , this would lead serious security threat
3.
Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally.

All constant strings that appear in a class are automatically interned. You only need to intern strings when they are not constants, and you want to be able to quickly compare them to other interned strings.
String str1 = "Test";
String str2 = "Test";
System.out.println(str1==str2);
System.out.println(str1.intern()==str2.intern());
String str3 = new String("Test");//created in heap and not added into string pool
String str4 = new String("Test");
System.out.println(str3==str4);
System.out.println(str3.intern()==str4.intern());
System.out.println("Hel"+"lo"=="Hello");
When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.
String s = new String("Test");
does not  put the object in String pool , we need to call String.intern() method which is used to put  them into String pool explicitly.

No comments:

Post a Comment