String is Immutable means that once it is created a
Following program contains 3 test cases to illustrate that the String is immutable
The above output of t1 and t2 test case clearly shows that String is changing so it cannot be immutable. But that's because we are not looking at the memory in the way its stored.
Here, str1 is a reference variable that points to "is this constant" String Object
Now
with this statement, str1 points to "a new value" String Object and "is
this constant" String object is now not linked to str1 reference
variable.
In 3rd test case, we are using another reference variable str2 also to link to the "is this constant" String Object and lets see what happens to the String Object.
From this output its clear, that String object is immutable, since str2 is still pointing to "is this constant" String Object. So whenever a string is changed, its just that the reference variable is pointing to a new String object and the old String object hasn't changed.
String
object cannot be changed.Following program contains 3 test cases to illustrate that the String is immutable
public class stringImmutable { public static void main(String[] args) { stringImmutable si1 = new stringImmutable(); for (String s: args) { System.out.println(s); } if(args.length>0) { if(args[0].equals("t1")) si1.t1(); else if(args[0].equals("t2")) si1.t2(); else if(args[0].equals("t3")) si1.t3(); } } public void t1() { //In 1st test case, the str1 is assigned a String and then later a new string String str1="is this constant"; System.out.println("str1>>>"+str1+"<<<"); //attempting to change the above str1; //String str1="a new value"; // throws error: // Error: variable str1 is already defined in method t1() // so another way to bypass the above error String str3="a new value"; str1 =str3; System.out.println("str1>>>"+str1+"<<<"); } public void t2() { //In 2nd test case, similar to above test String str1="is this constant"; System.out.println(">>>"+str1+"<<<"); //attempting to change the above str1; str1="a new value"; System.out.println(">>>"+str1+"<<<"); } public void t3() { // In 3rd test, str1 is declared and saved to str2,
// and then str1 is modified to new content String str1="is this constant"; String str2= str1; System.out.println("str1>>>"+str1+"<<<"); System.out.println("str2>>>"+str2+"<<<"); //attempting to change the above str1; str1="a new value"; System.out.println("str1>>>"+str1+"<<<"); System.out.println("str2>>>"+str2+"<<<"); } }
Output
$java stringImmutable t1 t1 str1>>>is this constant<<< str1>>>a new value<<<
$java stringImmutable t2 t2 >>>is this constant<<< >>>a new value<<
String str1="is this constant";
str1="a new value";
Output
$java stringImmutable t3 t3 str1>>>is this constant<<< str2>>>is this constant<<< str1>>>a new value<<< str2>>>is this constant<<<
String str1="is this constant"; String str2= str1;
str1="a new value";