tags:

views:

121

answers:

6

How-Do/Can I set the value of a String object in Java (without creating a new String object)?

Thanks, Chenz

+11  A: 

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.

Mark Byers
+1  A: 

Strings are immutable so you cannot change the value of an already created string.

+4  A: 

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

StudiousJoseph
A: 

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.

extraneon
A: 

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.

Christian Ullenboom
It is **always** a bad idea. If you need mutable strings, use `StringBuilder` instances instead.
Stephen C
A: 

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.

Michael Shopsin