Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String / string =>mutable?

 
Willie Toma
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The folloing statement is true: "The String class represents an immutable string."
Is it true that the string class represents a 'mutable' string?
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All Strings are immutable. Once created they can NOT be modified in any way.
This is to allow for some cute little "optimizations" in the JVM. Specifically the re-use of defined Strings. If you define the String "String yes = "Y"; in lots of places, the JVM only makes ONE object for it and points all the various uses at the same object. This is fine if you know that it can never change.
However, if multiple uses are all pointing at the same String value - it would be catastrophic if one of the uses tampered with the thing.
Instead there is a StringBuffer class for cases where you know that the object is going to change values.
 
Willie Toma
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you cannotate two strings and store the result in a new object, does the new object point to the old locations? Or, store the result of f and k?
String f = "Bellis";
String k = "simo!";
String r = f + k;
System.out.println(r); Bellissimo!
Forget about it!
Thanks Cindy, your the greatest.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A third object is made that r points to.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic