i

JAVA Complete Course

String Buffer and String Builder classes

We have couple of examples and operations on Strings. As we have already mentioned in the beginning strings are immutable objects which means that they are not changeable and any operation, for example concatenation, is giving another new object instead of changing existing one. So there are some classes which are created as a peer of String in order to modify existing strings or build strings dynamically with concatenating in a memory efficient way. One of such classes is StringBuffer.

StringBuffer represents character sequence which is growable and writable. StringBuffer may contain characters and substrings inserted in the middle or appended to the end. Each method in StringBuffer class is synchronized which means that it is thread safe class, we will cover this topic when we will speak about multithreading.

Let’s cover few methods of StringBuffer class:

insert( ): This method is used to insert string at the specified index position. Below are the few examples of it:

Here, the first parameter (index) specifies the place (index in the array of chars) at which point the string will be inserted into after invoking StringBuffer object.

reverse( ): It is used to reverse the characters within a StringBuffer object. This method returns the object on which it was called in a reversed form.

delete( ) and deleteCharAt( ): These methods are used to remove characters within a StringBuffer. The delete( ) method removes a sequence of characters from the invoking object. Here, first parameter (startIndex) specifies the index of the first character to be deleted, and the second parameter (endIndex) specifies an index one past the last character to be deleted. Thus, the substring deleted runs from start Index to endIndex–1. The resulting StringBuffer object is returned. The deleteCharAt( ) method removes the character at the index specified method parameter. It returns the resulting StringBuffer object. Below are the signatures of these methods

Another class is StringBuilder. It is same as StringBuffer except for one important difference: its methods are not synchronized, which means that it this class is not thread-safe. The belefit of StringBuilder over StringBuffer is performance. However, in cases of  multithreading, we have to use StringBuffer rather than StringBuilder.

One of the most widely used method if StringBuilder class is append(String s), let’s visit example of using it.

The output of this program is: This is dynamically created string