Java – StringBuffer & StringBuilder

StringBuffer and StringBuilder

You already know by now that Strings in Java are immutable. This means we can’t modify them once created. Hence any changes to them would create a new object in the memory.

 

We would cover the following:

  1. Difference between StringBuilder and StringBuffer
  2. How to Create a StringBuilder
  3. Methods of the StringBuilder Class
  4. Some Examples
  5. Other StringBuilder Methods
  6. Watch the Video

 

 

1. Difference between StringBuilder and StringBuffer

However, Java provides the StringBuilder and StringBuffer classes to handle this problem. So with this classes, you can create a string that you can modify.

 

What then is the difference between the two?

Note the following differences:

 

  • StringBuffer methods are thread-safe while StringBuilder methods are not
  • StringBuffer methods are Synchronized while StringBuilder methods are not
  • StringBuilder object perform better (are faster) than StringBuffer
  • You will always have  to use StringBuilder. This is recommended unless thread-safety is required.

 

 

2. How then do you create a StringBuilder Object?

You do this by using the new keyword and calling the StringBuilder constructor. Then you provide a new string. The code below illustrates this

 

public class StringBuilderTest {

	public static void main(String[] args) {
		//Creating a StringBuilder object
		StringBuilder sbd = new StringBuilder("Java");
		sbd.append(" Tutorials ");
		
		//Creating a StringBuffer object
		StringBuffer sbf = new StringBuffer("Java");
		sbf.append(" Tutorials");
		
		System.out.println(sbd);
		System.out.println(sbf);
	}
}

Listing 1.0: StringBuilder and StringBuffer

 

Code in Listing 1.0 creates a StringBuilder string. The next line then appends additional string to the end of the string. We do the same for the StringBuffer

You can see that StringBuilder and StringBuffer are exactly the same in terms of syntax. So based on this, we are just going to focus on StringBuffer.

 

 

3. Methods of StringBuilder Class

We have a number of useful method provided by the StringBuilder class. You probably should take some time to master some of these methods.

They are listed in Table 1.0 below.

 

SN Methods and brief description
1 append(String s)Modifies a string by appending a new string to the end. Takes boolean, char, int, long, Strings etc as parameter. It returns the modified StringBuffer object.
2 reverse()Reverses the value of the given StringBuffer object. For example, abcd becomes dcba. It then returns the modified object.
3 delete(int start, int end)Deletes a string from the given StringBuilder object starting from the start index to the end index.
4 insert(int offset, int i)Inserts a string s into  the position specified by the offset.
5 replace(int start, int end, String str)Replaces the characters in the substring of the StringBuilder with characters in the given String.

Table 1.0: StringBuilder Methods

 

 

4. Some Examples 

Let’s now demonstrate how some of these methods work. Take a look at the program below. I recommend you make sure to try it yourself. Also look at the comments to see exactly what is happening.

Already you know about the append method. So we  examine other methods.

 

public class StringBuilderTest {

	public static void main(String[] args) {
		StringBuilder sbd = new StringBuilder("Java");
		
		//1. The append method
		sbd.append(" Tutorials ");
		System.out.println("1. : " + sbd);
		
		//2. The reverse method
		sbd.reverse();
		System.out.println("2. :" + sbd);
		
		//3. Reverse it back to normal
		sbd.reverse();
		System.out.println("3. : " + sbd);

		//4. Deletes the first 4 characters
		sbd.delete(0, 4);
		System.out.println("4. :" + sbd);
		
		//5. Insert JavaScript in the first index of 0
		sbd.insert(0, "JavaScript");
		System.out.println("5. : " + sbd);
		
		//6. Replace JavaScript with AngularJs
		sbd.replace(0, 10, "AngularJS");
		System.out.println("6. : " + sbd);
	}
}

Listing 1.1: Demonstrating the StringBuilder Methods

 

I have added comments to clarify the code. So if you run this code, you will get the output given below.

 

1. : Java Tutorials 
2. : slairotuT avaJ
3. : Java Tutorials 
4. : Tutorials 
5. : JavaScript Tutorials 
6. : AngularJS Tutorials 

Output of Listing 1.1 Program

 

 

5. Other StringBuilder Methods

I then provide a list of other methods in the StringBuilder class. So try to play around with them. In this way you can get your head around them. And it becomes  clearer to you as well.

Also note that most of these methods apply also to the String class.

 

SN Method and description
1 capacity()

Returns the current capacity of the String buffer.

2 charAt(int index)

The given character of the string currently represented by the string buffer, as specified by the index argument, is returned. Returns an int.

3 void ensureCapacity(int minimumCapacity)

Sets the the capacity of the buffer is at least equal to the specified value.

4 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

Characters are copied from this string buffer into the destination given by the char array dst.

5 indexOf(String str)

Returns the particular index within the calling string of the first occurrence of the given substring str.

6 int indexOf(String str, int fromIndex)

Returns the index within the calling string of the first occurrence of the given substring str, starting at the specified index.

7 int lastIndexOf(String str)

Returns the index within the calling string of the rightmost occurrence of the given substring str.

8 int lastIndexOf(String str, int fromIndex)

Returns the index within the calling string of the last occurrence of the given substring str.

9 int length()

Returns the lengthof this StringBuilder. That is number of characters

10 void setCharAt(int index, char ch)

Sets the specified index of this string builder is set to ch.

11 void setLength(int newLength)

Sets the length of this StringBuilder.

12 CharSequence subSequence(int start, int end)

Returns a new character sequence that is a subsequence of this calling string.

13 String substring(int start)

Returns a new String that contains a subsequence of characters currently contained in this StringBuilder. The substring begins at the specified index and extends to the end of the StringBulder.

14 String substring(int start, int end)

Returns a new String that contains a subsequence of characters currently contained in this StringBuilder.

15 String toString()

Converts to a string representing the data in the calling StringBuilder.

Table 1.1: List of other StringBuilder Methods

 

Watch the Video