Quata 6: String Concatenation

feature image

Quata 6: String Concatenation

Let’s get right to it, shall we? Would any of the following ways of converting a list of names into a semi-colon-separated string pass your meticulous review? Yes, the trailing semi-colon is okay. Don’t worry about it.

String names = "";
for (String name : customerNames) {
  names += name + ";";
}

StringBuffer names = new StringBuffer();
for (String name : customerNames) {
  names.append(name + ";");
}

StringBuilder names = new StringBuilder();
for (String name : customerNames) {
  names.append(name + ";");
}

Which way is correct?

If you think it’s the first one, raise your hand.

I hope you didn’t. The String class is immutable. While the syntax does not reveal it, this actually creates a new String object each time. And since you’re assigning the new value to the same variable, you’re basically discarding the old value. That memory churn hurts my heart, doesn’t it yours?

What about the second one?

Keep that hand down. This is obviously a local variable (well, at least I hope it’s obvious), which should never need synchronization. StringBuffer operations are synchronized, which adds unnecessary overhead in this case. I still see this from time to time. The developer must not have heard about StringBuilder, which leads me to the next one.

If you think the third one is correct, raise your hand.

I’m sorry, but you’re still wrong.

While StringBuilder is the better class to use, the String concatenation inside the append() method is actually hurting your code. It’s creating a temporary String object, which is then appended to the StringBuilder object. And, you guessed it, it’s discarded right after. Do this instead:

StringBuilder names = new StringBuilder();
for (String name : customerNames) {
  names.append(name).append(';');
}

Note that the String concatenation operator does have its place. Consider the following:

String displayName = "First name: " + firstName + "; Last name: " + lastName;

That’s perfectly all right. There’s no loop here. We need one String object and that’s what we get. The bytecode generated will actually use StringBuilder internally. The above code will be compiled into the equivalent of:

String displayName = new StringBuilder().append("First name: ").append(firstName).append("; Last name: ").append(lastName).toString();

“There ” + “you ” + “have ” + “it.”

Leave a Reply

Your email address will not be published. Required fields are marked *

Post navigation

Previous Post :