简体   繁体   中英

Strings Immutability

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?

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.

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

name.replace('a', 'i');

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.

If your code is name="name"; name.replace('a', 'i'); //assignment to String variable name is neglected System.out.print(name) 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:

String name = "name";
String r    = name.replace( 'a', 'i' );
System.out.println( name );// not changed 
System.out.println( r    ); // new, different string 

If you assign the new ref to r, the original object wont change.

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM