Strings Immutability

2020-04-14 07:29发布

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?

4条回答
【Aperson】
2楼-- · 2020-04-14 07:39

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.

查看更多
smile是对你的礼貌
3楼-- · 2020-04-14 07:42

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.

查看更多
做个烂人
4楼-- · 2020-04-14 07:42

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.

查看更多
够拽才男人
5楼-- · 2020-04-14 07:45

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.

查看更多
登录 后发表回答