Kraken
Kraken

Reputation: 24213

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?

Upvotes: 2

Views: 228

Answers (4)

sidharth
sidharth

Reputation: 61

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.

Upvotes: 0

OscarRyz
OscarRyz

Reputation: 199205

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.

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285415

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.

Upvotes: 1

Sky Kelsey
Sky Kelsey

Reputation: 19280

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.

Upvotes: 6

Related Questions