I was told that strings in java can not be changed.What about the following code?
name="name";
name=name.replace('a', 'i');
Does not it changes name
string?
Also, where is the implementation of the replace(); compareTo(); equals(); provided?
I am just using these functions here, but where actually are they implemented?
This is a classic case of confusing a reference variable (name) with a String object it refers to ("name"). They are two very different beasts. The String never changes (ignoring reflection type kludges), but a reference variable can refer to as many different Strings as needed. You will notice that if you just called
nothing happens. You only can see a change if you have your name variable assigned to a different String, the one returned by the
replace
method.String.replace() returns a new String.
"name" is a reference to a String object, so it can be reassigned to point to name.replace(), but it will be pointing to a new object.
Here is the javadoc for String, where you can find out what all the methods do.
If your code is
name="name"; name.replace('a', 'i'); //assignment to String variable name is neglected System.out.print(name)
output:
name
this is because the
name.replace('a','i')
would have put the replaced string,nime
in the string pool but the reference is not pointed to String variable name.Whenever u try to modify a string object,
java checks, is the resultant string is available in the string pool
if available the reference of the available string is pointed to the string variable
else new string object is created in the string pool and the reference of the created object is pointed to the string variable.
Try this and see it for your self:
If you assign the new ref to r, the original object wont change.
I hope this helps.