How-Do/Can I set the value of a String object in Java (without creating a new String object)?
Thanks, Chenz
How-Do/Can I set the value of a String object in Java (without creating a new String object)?
Thanks, Chenz
There are no "set" methods on String
. Strings are immutable in Java. To change the value of a String
variable you need to assign a different string to the variable. You can't change the existing string.
(without creating a new String object)
Assigning doesn't create a new object - it copies the reference. Note that even if you write something like this:
s = "hello";
it won't create a new string object each time it is run. The string object will come from the string pool.
Actually there is no way to do that in Java, the String objects are immutable by default.
In fact, that's one of the reason why using the "+"
concatenation operator like "str1" + "str2"
is terribly inefficient, because what it does is copy every string in order to produce a third one.
Depending on your need you should consider using StringBuilder
It depends a bit on your definition of object. If you mean the reference, no. A reference is always created. If you mean the memory used by the characters, sure.
Strings are interned (if possible) which means that in an assignment:
String s1 = "Hello";
String s2 = "Hello";
there are 2 references (pointers to a memory location), but Hello
is in memory on only 1 place. This is one of the reasons Strings can't be modified.
Sure you can access the internal char array via reflection. But it's usually a bad idea to do so. More on http://www.eclipsezone.com/eclipse/forums/t16714.html.
The String object is immutable in Java so any changes create a new String object. Use a StringBuilder if you want to make changes to a string like object without creating new objects. As a bonus the StringBuilder allows you to preallocate additional memory if you know something about the eventual length of your string.