Preeti,
The issue of a string being immutable is typically difficult for a new
Java programmer to grasp, especially when it appears that a simple assignment statement changes the value of the string. However, one of the key concepts that comes into play is the idea that a "string" is not a "String".
A "string" (not capitalized) is just a series of characters. However, a "String" (capitalized) is a Java object.
If you recall, an object encapsulates data and methods. In a String object, the encapsulated data are a series of characters...a string. But--and this is important--you can't get into that String object to
change the series of characters of the data string. You can get the series of letters (the encapsulated string) through methods that are in the String object, and you can get a sub-set of the encapsulated string by methods in the String ojbect. But
there is no method in the String object that allows you to
change the string data that is encapsulated in the String object.
Like I said in the start, this is not an easy concept for beginners to grasp, but it is fundamental.
Although code such as the examples you displayed in your original posting might suggest that strings are being changed, what is really happening is that the references (the variables such as
fname and
lname) to objects are changing what they refer to...old String objects are being discarded and new objects are being assigned to the same references. And this is done by having the references (
fname and
lname) point to
different areas of memory!
The fact that the original String objects have been discarded and replaced by new String objects means you haven't
changed the encapsulated string data of your original String objects...you have discarded them (the original String objects) and replaced them with new String objects.
As Noah wrote, "strings are immutable."
If you'd like to read more about immutable objects, check out the free download of Bruce Eckel's book, "Thinking In Java" at
http://www.bruceeckel.com Look at pages 1052+.
Now, have I made it as clear as mud?