Wednesday 14 May 2014

StringBuffer re-initialization with setLength method

Often, we need to re-initialize a string with a value other than the one it was initialized with. Using StringBuffer here is recommended if the original string is not needed once its value has been changed.

A common way to re-initialize a StringBuffer obj is to write:

obj = new StringBuffer ();

What this does is create a new object itself and reassigns the reference obj to refer to the new object.

An optimized approach of achieving the same goal is to set the length of the obj to zero.

obj.setLength(0);

This does not create a new object but instead resets the value of the same StringBuffer object, obj.





No comments:

Post a Comment