Can I set the value of a String in Java without using a constructor?
How-Do/Can I set the value of a String object in Ja开发者_Go百科va (without creating a new String object)?
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
Strings are immutable so you cannot change the value of an already created string.
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.
I stumbled across this question because i have to set a string within an "enclosing type" - an anonymous type. But all variables i want to set inside and use outside must be final.
The simple solution is to use StringBuilder - it's an mutable String.
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.
精彩评论