Java string immutability

The theory of the immutability of the String class says that once created, a string can never be changed. Real life experience with Java programming implies that this is not true.

Take the following code
EX1:
public class ImString{
public static void main(String argv[]){

       String s1 = new String("Hello");

       String s2 = new String("There");

       System.out.println(s1);

       s1=s2;

       System.out.println(s1);
       }
}
If Strings cannot be changed then s1 should still print out Hello, but if you try this snippet you will find that the second output is the string "There". What gives?

The immutability really refers to what the String reference points to. When s2 is assigned to s1 in the example, the String containing "Hello" in the String pool is no longer referenced and s1 now points to the same string as s2. The fact that the "Hello" string has not actually been modified is fairly theorectical as you can no longer "get at it".

The objective asks you to recognise the implications of the immutability of strings, and the main one seems to be that if you want to chop and change the contents of "strings" the StringBuffer class comes with more built in methods for the purpose.

Because concatenating string causes a new string to be instantiated "behind the scenes", there can be a performance overhead if you are manipulating large numbers of strings, such as reading in a large text file. Generally String immutability doesn't affect every day programming, but it will be questioned on the exam. Remember whatever round about way the question asks it, once created a String itself cannot be changed even if the reference to it is changed to point to some other String. This topic is linked to the way Strings are created in a "String pool", allowing identical strings to be re-used.


EX2:


public static void main(String args[]) {


String lc = "lowercase";


lc.toUpperCase();


System.out.println(lc);


}



The result will still be "lowercase". Because string object lc is not referenced to any other string object, and the contents of string object lc can not be changed.

评论

此博客中的热门博文

Nu förbjuder Kina handel med elfenben

Fader av pingyins

Kineserna vill köpa Volvos kompetens