Strings are immutable in Java. What exactly does it mean?
First, let us understand the meaning of the word “immutable”. Immutable means something which can’t be changed with time.
In JAVA, strings are immutable. Let’s understand this with an example.
public class practice {
public static void main(String[] args) throws IOException {
String name = "Vishal";
name.concat(" Khanna");
System.out.println(name);
So what do you think the output of the above program is? The output will be only Vishal. This proves that in JAVA strings are immutable.
Let’s see another code snippet:
public class practice {
public static void main(String[] args) throws IOException {
String name = "Vishal";
name = name.concat(" Khanna");
System.out.println(name);
Now guess the output of the above code snippet. Will it be Vishal or Vishal Khanna? The correct answer is Vishal Khanna.
But wait, I just said that strings are immutable in JAVA. Am I contradicting what I said earlier? How come the output is Vishal Khanna?
When the above code is executed, the VM takes the value of the String name
i.e. “Vishal” and appends “Khanna”, giving us the value “Vishal Khanna”. However, a new string object is created with the same reference variable name. Hence when we print the name variable it gives us “Vishal Khanna” instead of “Vishal”.
An important point to note is that we have lost theString name
having the value “Vishal” because now the name
refers to a new object having the value “Vishal Khanna”. Almost every method, applied to a String
object, in order to modify it, creates a new String
object.
Another important point is to note is that in JAVA string object is immutable however, its reference variable is not. So that’s why, in the above example, the reference was made to refer to a newly formed String
object.