StringBuffer over String Class


String myStr = “SchoolHoood”;
myStr = myStr.concat(” – Learn to Enjoy”);
myStr = myStr.concat(” – For 5 to 55.”);

Since strings are immutable in java, the above codes makes 2 hanging string objects in heap namely:
1. SchoolHood
2. SchoolHood – Learn to enjoy
Of course the final string “SchoolHoood – Learn to Enjoy – For 5 to 55.” will have a reference var as myStr.

If lot many modifications are required on a string, StrinBuilder/StringBuffer should be preferred over just plain String class. This is to avoid the loosing of strings in the heap-pool and hence saving the memory. For detail read Immutable String in Java.

The above code could be rewritten as:
StringBuffer myStrBuff = nw StringBuffer(“SchoolHoood”);
myStrBuff.append(” – Learn to Enjoy”);
myStrBuff.append(” – For 5 to 55.”);

Since append method is invoked on the StringBuffer object “myStrBuff” itself, hence append happens to be on the same string. Thus StringBuffer/SringBuilder objects can be modified over and over again without leaving behind a discarded String objects.

These two methods are used widely in case of FILE I/O because there you need to treat a large amount of data as a single unit. Say for example , while reading a file line by line — youStrBuilderObj.append(lineContent) — will make you to deal with data easily.

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s