Immutability of the "String" class in Java
Consider the following code snippet:
----------------------------
String a = "First";
System.out.println(a);
----------------------------
The output is: First
Now, I use the string concatenation operator "+" as:
----------------------------
String a = "First";
a = a + " Second"; //Creates a new String object
System.out.println(a);
----------------------------
The output is: First Second
The string concatenation operator "+" implicitly creates a new String object and the reference to the old one is lost, thus the value of String object cannot be changed after it has been created (i.e. it's Immutable).
No comments:
Post a Comment