String and StringBuilder

In this blog post, I’ll talk about String and StringBuilder.

String is immutable. Immutable means its contents cannot be altered.

String message = "I Love You";

message = "I Love You Beverly";

Consider the code above, the value of the message variable has not altered but actually java creates two different objects.

“I Love You” value does not garbage collected right away after being deferenced. The value is actually stored in “String Pool”, a special memory for Strings.

This is what happens in the String Pool after the code above is executed,
After the “I Love You” value is being deferenced, the value still exists in the String Pool. So that if the value is needed elsewhere in the application, java does not need to instantiate new String object.

For example,
Assuming the “I Love You” value is needed somewhere in the application, java does not instantiate new String object, it rather finds the existing value in the String Pool.

This helps with performance if certain strings are used over and over in the application because there are no cost of repeated String instantiation. However things get complicated if we try to “modify” a string.

String greeting = "Happy"
greeting = greeting + " ";
greeting = greeting + "Birthday";
greeting = greeting + " ";
greeting = greeting + "Beverly";

As what I’ve discussed earlier, Strings are immutable, you can never modify a String, instead you create new one.

For the code above 9 String objects are instantiated:

  1. “Happy”
  2. ” “
  3. “Happy “
  4. “Birthday”
  5. “Birthday “
  6. “Beverly”
  7. “Happy Birthday”
  8. “Happy Birthday “
  9. “Happy Birthday Beverly”

This is what happen in the String Pool


This could lead to large memory consumption because of multiple String instantiation. In the other words, performance will suffer if you will use String that will handle multiple string manipulations.

If your application needs to handle a lot of String manipulation, consider using StringBuilder.

StringBuilder is mutable sequence of characters unlike String.

Since StringBuilder is mutable, the contents of the strings can be altered without making multiple instantiation, hence, performance will not suffer.

For StringBuilder click here.


Use String if have only few String manipulation like concatenating short messages.

If a string-manipulation might leave a lot of objects in the StringPool, or performance is a high priority, consider StringBuilder.


One thought on “String and StringBuilder

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s