Monday, March 12, 2007

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:


_________________________________________________________________________________________________________________

"Look at the sky. We are not alone. The whole Universe is friendly to us and conspires only to give the best to those who dream and work."

- Dr. A P J Abdul Kalam
_________________________________________________________________________________________________________________