Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java immutable strings confusion

Tags:

java

If Strings are immutable in Java, then how can we write as:

String s = new String();
s = s + "abc";
like image 545
rainmaker Avatar asked Jan 19 '12 23:01

rainmaker


4 Answers

Strings are immutable.
That means that an instance of String cannot change.

You're changing the s variable to refer to a different (but still immutable) String instance.

like image 81
SLaks Avatar answered Oct 19 '22 05:10

SLaks


Your string variable is NOT the string. It's a REFERENCE to an instance of String.

See for yourself:

String str = "Test String";
System.out.println( System.identityHashCode(str) ); // INSTANCE ID of the string

str = str + "Another value";
System.out.println( System.identityHashCode(str) ); // Whoa, it's a different string!

The instances the str variable points to are individually immutable, BUT the variable can be pointed to any instance of String you want.

If you don't want it to be possible to reassign str to point to a different string instance, declare it final:

final String str = "Test String";
System.out.println( System.identityHashCode(str) ); // INSTANCE ID of the string

str = str + "Another value"; // BREAKS HORRIBLY
like image 40
Gabriel Bauman Avatar answered Oct 19 '22 04:10

Gabriel Bauman


The first answer is absolutely correct. You should mark it as answered.

s = s+"abc" does not append to the s object. it creates a new string that contains the characters from the s object (of which there are none) and "abc".

if string were mutable. it would have methods like append() and other such mutating methods that are on StringBuilder and StringBuffer.

Effective Java by Josh Bloch has excellent discussion on immutable objects and their value.

like image 21
john.stein Avatar answered Oct 19 '22 06:10

john.stein


Immutable Classes are those whose methods can change their fields, for example:

Foo f = new Foo("a");
f.setField("b"); // Now, you are changing the field of class Foo

but in immutable classes, e.g. String, you cannot change the object once you create it, but of course, you can reassign the reference to another object. For example:

String s = "Hello";
s.substring(0,1); // s is still "Hello"
s = s.substring(0,1); // s is now referring to another object whose value is "H"
like image 30
Eng.Fouad Avatar answered Oct 19 '22 04:10

Eng.Fouad