String is Immutable in java


String is immutable class in java, any changes made to Sting class produces new String.



Diagram to show String is Immutable in java >

Program to demonstrate String is Immutable in java>
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ImmutableString {
   public static void main(String[] args) {
          String str="ab";
          System.out.println(str.concat("cd")); //abcd
          System.out.println(str); //ab
   }
}
/*OUTPUT
abcd
ab
*/

Let’s discuss step-by-step what will happen when program is executed >
String str= "ab";
No string with “ab” is there in string pool, so JVM will create string “ab” in string pool and str will be a reference variable which will refer to it.


str.concat("cd")
cd will be concatenated with ab and new string  “abcd”  will be formed. No string with “abcd” is there in pool, so JVM will create string “abcd” in string pool, but there won’t be any reference variable to abcd”  (we are using it only in system.out.println statement), meanwhile str will still be pointing to “ab”.


System.out.println(str);
str is referring to  “aband string abcdwill be eligible for garbage collection.




Another example>
What will happen when below 2 statements will execute >

String str= "ab";
str = "abcd";

String str= "ab";
No string with “ab” is there in string pool, so JVM will create string “ab” in string pool and str will be a reference variable which will refer to it.


str = "abcd";
No string with “abcd” is there in string pool, so JVM will create new string “abcd” in string pool and str will be a reference variable which will refer to it.

Now, String "ab" will stay in string pool but reference to it will be lost, and it will be eligible for garbage collection.


Advantages of String being immutable >

HashCode of string is cached - JVM caches the hashCode of very frequently used String in application. JVM need not to calculate hashcode again. Hence, performance of application is improved significantly.


Avoiding Security threats - String is used as parameter in many important java classes like network connection and file IO. If String wouldn't have been immutable, it would have posed serious security threat to application because any change made at one place could have also changed String passed in these classes as well (changes may have been done intentionally, may be for hacking purposes).


RELATED LINKS>

String pool/ String literal pool/ String constant pool in java

Creating Immutable class in java


Must read for you :
Labels:

No comments:

Post a Comment