Strings Immutability

此生再无相见时 提交于 2019-12-02 05:12:02

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/7494654/strings-immutability

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!