Reputation: 1
if we have these statements:
String S1 = "AAA";
S1 = "aaa";
this mean that the original value assigned to a specific property has't changed.(because the string class is immutable and S1 is an interned object).
now... if we have the following statements:
String S1 = new String("AAA");
S1="aaa";
this mean that the original value assigned to a specific property in string class has changed.(because the string class is immutable and S1 is not interned object)
is my understanding right?
Upvotes: 0
Views: 110
Reputation: 3710
No, String
object is immutable under any circumstances. When you call new String("foo")
this simply creates another one string with content of passed. So don't do this.
EDIT:
In the second case S1
isn't interned but this doesn't cancel its immutability. So String
assignment always doesn't change left object but simply rewrites reference.
Upvotes: 4
Reputation: 17675
Strings are immutable. That means that an instance of String cannot change. You're creating new variable to refer to a different but still immutable String instance.
it allows for changes to the string to branch off the original string in a change list sort of method
String s = new String();
An empty String object ("") is created. And the variable s refers to that object.
Upvotes: 1
Reputation: 63708
Adding to other answers,
String constructor that takes String object is a design flaw(It doesn't make sense to create an immutable instance twice) and is deprecated. Don't use it.
Upvotes: 1