Friday, 23 January 2015

Can You Change a Java String?

I read in a book that once you have created a Java String, you cannot change it so I decided to try it out myself:

andrew@UBUNTU:~/Java$ cat string_test.java
public class string_test
  {
  public static void main(String args[])
    {
    String str1 = "Andrew ";
    str1 = str1 + "was here";
    System.out.println("str1 = " + str1);
    }
  }
andrew@UBUNTU:~/Java$ javac string_test.java
andrew@UBUNTU:~/Java$ java string_test
str1 = Andrew was here
andrew@UBUNTU:~/Java$


At first glance, it looks as if you CAN change a String variable so I did a bit more reading. It seems that when you change a String, you are not altering the original variable. You are really creating a new variable to hold the updated value. If I can find some way to prove or disprove this statement, I will return to this post and update it accordingly.