avgvstvs
avgvstvs

Reputation: 6315

Are Strings also static: String creation within Methods

I know that at compile time when a String is created, that String will be THE string used by any objects of that particular signature.

String s = "foo"; <--Any other identical strings will simply be references to this object.

Does this hold for strings created during methods at runtime? I have some code where an object holds a piece of string data. The original code is something like

for(datum :data){
    String a = datum.getD();  //getD is not doing anything but returning a field

    StringBuffer toAppend = new StringBuffer(a).append(stuff).toString();

    someData = someObject.getMethod(a);
    //do stuff

}

Since the String was already created in data, it seems better to just call datum.getD() instead of creating a string on every iteration of the loop.

Unless there's something I'm missing?

Upvotes: 3

Views: 127

Answers (3)

Mark Peters
Mark Peters

Reputation: 81074

String instances are shared when they are the result of a compile-time constant expression. As a result, in the example below a and c will point to the same instance, but b will be a different instance, even though they all represent the same value:

String a = "hello";
String b = hell() + o();
String c = "hell" + "o";

public String hell() {
   return "hell";
}

public String o() {
   return "o";
}

You can explicitly intern the String however:

String b = (hell() + o()).intern();

In which case they'll all point to the same object.

Upvotes: 7

chustar
chustar

Reputation: 12465

You are correct that strings are immutable so all references to the same string value use the same object. As far as being static, I do not think Strings are static in the way you describe. The Class class is like that, but I think it is the only object that does that.

I think it would be better to just call the datum.getD() since there is nothing that pulling it out into its own sting object gains for you.

If you do use the datum.getD() several times in the loop, then it might make sense to pull the value into a String object, because the cost of creating a string object once might be less than the cost of calling the getD() function multiple times.

Upvotes: -2

Nathan Hughes
Nathan Hughes

Reputation: 96394

The line

 String a = datum.getD();

means, assign the result of evaluating datum.getD() to the reference a . It doesn't create a new String.

Upvotes: 3

Related Questions