What are StringBuffer and StringBuilder Classes?

As we learned in the Java String class tutorial, the strings are immutable. That means, once created, a string cannot be changed in Java programming.

In certain scenarios, you require the ability to modify strings to add, remove, replace, or perform other operations. For that, StringBuffer and StringBuilder is the answer.

So, both (StringBuffer and StringBuilder) classes allow creating the mutable sequence of characters. At any point in the program, you may change the content of StringBuffer/StringBuilder objects by using methods.

Besides, concatenating strings as using the String class requires creating new objects. This makes strings slower as compared to StringBuilder/StringBuffer classes.

Now, as you understand the difference between String and Java StringBuilder / StringBuffer classes, the next question is how we may compare the StringBuilder vs StringBuffer?

Difference between StringBuilder and StringBuffer Java

  • The StringBuffer class methods are thread-safe / synchronized.
  • The StringBuilder is not synchronized or thread-safe.
  • StringBuilder is faster than StringBuffer – so it is recommended to be used officially.
  • However, if thread-safety is important for your program, then you should use the StringBuffer class.

Otherwise, both classes work the same way – for example, principal operations are the insert and append methods that both support.

In the next section, I will show you how to use these classes for different string operations like appending a substring, insert, replace, and other methods with examples.

An example of creating a string with StringBuffer append method

In this example, StringBuffer object is created with a string value.  The append method can be used for adding a substring at the end of this string.

public class string_b {

          public static void main(String args[]) {

                 StringBuffer s_buffer = new StringBuffer("Hello mutable string. ");

                

                 System.out.println(s_buffer);

                 s_buffer.append("Another string added");

                 System.out.println(s_buffer);

     }



}

Output:

Java StringBuffer

You saw a string was created with the append method and it was displayed. After that, the append method was used again and another string was appended to the end of the existing string.

Using append method of StringBuilder class

Almost the same example as above except a StringBuilder object is created and its append method is used:

public class string_b {

          public static void main(String args[]) {

                 StringBuilder s_builder = new StringBuilder("Hello mutable string by StringBuilder. ");

                

                 System.out.println(s_builder);

                 s_builder.append("Another string added");

                 System.out.println(s_builder);

     }



}

The Output:

Hello mutable string by StringBuilder.

Hello mutable string by StringBuilder. Another string added

Objects to string conversion example

When working with strings, one of the important aspects is converting numbers like int, float, double (primitive or objects) into the strings. This may be required for concatenation or for some other reason.

By using the append method of StringBuffer and StringBuilder classes, not only strings can be appended (as shown in the first example) but other objects as well.

The append method can be used for other objects as follows:

Method Description
append(boolean bln) Adds Boolean argument’s string representation to the end of the sequence.
append(char chr) Adds the char argument’s string representation to the end of the sequence.
append(char[] str) Adds the char array argument’s string representation to the end of the sequence.
append(double dbl) Adds the double argument’s string representation to the end of the sequence.
append(float flt) Adds the float argument’s string representation to the end of the sequence.
append(int i) Adds the int argument’s string representation to the end of the sequence.
append(long lng) Adds the long argument’s string representation to the end of sequence.
append(Object obj) Adds the object’s argument’s string representation to the end of sequence.
append(StringBuffer sb) Adds the string buffer to the end of sequence.

In the following demo, a string is created which is followed by appending strings, int, float and double primitive types and finally displaying the resultant string.

Have a look:

public class string_b {

          public static void main(String args[]) {

                 int x = 510;

                 float y = 311.252f;

                 double z = 14578741.14d;

                

                 StringBuffer sb_conv = new StringBuffer("an int = ");

                

                 //Appending in StringBuffer object - strings, int, float and numbers



                 sb_conv.append(x);

                 sb_conv.append(" and a float: ");

                 sb_conv.append(y);

                 sb_conv.append(" and finally double:");

                 sb_conv.append(z);

                

                 //Display the resultant string

                 System.out.println(sb_conv);

        }

}

The output:

an int = 510 and a float: 311.252 and finally double:1.457874114E7

An example of StringBuilder insert method

The insert method() of StringBuilder and StringBuffer classes is used to insert the given string or other objects like int, char, long, float, etc. at the given position, unlike the append method that adds at the end of the specified string.

See an example below for inserting a string by using Java StringBuilder insert method:

public class string_b {

          public static void main(String args[]) {

                 StringBuilder s_builder_ins = new StringBuilder("Hello mutable string by StringBuilder. ");

                

                 System.out.println("Original String: " +s_builder_ins);

                 s_builder_ins.insert(24, "Java ");

                 System.out.println("After insert method: " +s_builder_ins);

     }



}

The Output:

Original String: Hello mutable string by StringBuilder.

After insert method: Hello mutable string by Java StringBuilder.

You can see, the word Java is added at the 24th position in the original string.

The same you may use for the StringBuffer class for inserting a string or other object at the given position.

Removing characters in a string by the delete method

The delete method of StringBuilder and StringBuffer classes can be used for removing the characters in the substring. You may specify the start and end position in the delete method as follows:

delete(int start, int end)

Have a look at a demo below that uses StringBuffer delete method:

public class string_b {

          public static void main(String args[]) {

                 StringBuffer sBuf = new StringBuffer("Hello mutable string by Java. ");

                

                 System.out.println("Original String: " +sBuf);

                 sBuf.delete(6,20);

                 System.out.println("After delete() method: " +sBuf);

     }



}

The output of the code is:

Original String: Hello mutable string by Java.

After delete() method: Hello  by Java.

For using StringBuilder delete method, just replace StringBuffer to StringBuilder in the example.

The replace method example

The replace method can be used for replacing a part of the string. This is how the replace method can be used for both classes:

replace(int start, int end, String str)

The replace method takes the start and end position in the string as int type. The third parameter is the string to be replaced with.

So, from start to end position the existing characters will be replaced by the given str. See the following example for learning more about this:

public class string_b {

          public static void main(String args[]) {

                 StringBuilder sBui = new StringBuilder("Hello mutable string by Java. ");

                

                 System.out.println("Before Replace: " +sBui);

                

                 //Using replace method

                 sBui.replace(6,30,"World!");

                 System.out.println("After replace() method: " +sBui);

     }



}

The output:

Before Replace: Hello mutable string by Java.

After replace() method: Hello World!

You see, the “World” is replaced by the “string by Java.”.

Java StringBuilder/StringBuffer reverse method example

For reversing the order of characters in the string, you may use the reverse method of StringBuilder and StringBuffer class. The syntax of using the reverse() method is:

public StringBuilder reverse()

Or

public StringBuffer reverse()

See an example below:

public class string_b {

          public static void main(String args[]) {

                 StringBuilder sBui = new StringBuilder("Reversed");

                

                 System.out.println("Before reverse method: " +sBui);

                

                 //Using reverse() method

                 sBui.reverse();

                 System.out.println("After reverse() method: " +sBui);

     }



}

The output:

Before Replace: Reversed

After replace() method: desreveR

The charAt method example

The chartAt method of StringBuilder and StringBuffer classes returns the char value for the given index position. The index is given as integer that starts at 0.

charAt(int index)

The following example shows how you may use the charAt method:

public class string_b {

          public static void main(String args[]) {

                

                 StringBuilder sb_charAt = new StringBuilder("How to use the charAt methdod?");

                 //How to use charAt method  

        

               System.out.println("The chara at 0 index : " +sb_charAt.charAt(0));

               System.out.println("The char at 12 index : " +sb_charAt.charAt(12));

               System.out.println("The char at 35 index : " +sb_charAt.charAt(35));

        }

}

The output:

Java StringBuilder charAt

In the output graphic, the character returned for position 0 in the specified string is ‘H’ and at 12 is ‘h’. For the index position 35, an error is thrown: java.lang.StringIndexOutOfBoundsException.

The rules for charAt method are:

  • The value must be 0 or greater for the index argument in charAt method
  • If a value is negative or greater than the length of the string, the java.lang.StringIndexOutOfBoundsException is raised (as in above example)
  • The index starts at 0.

Using the indexOf StringBuilder/StringBuffer method example

The indexOf method returns the index of the first occurrence of the given substring. You may use this method with two variations as follows:

indexOf(String str)

indexOf(String str, int fromIndex)

In the first way of using the indexOf method, it returns the first occurrence from the beginning of the specified string.

The second way searches the given str from the specified index in the string.

See an example below:

StringBuilder sbindOf = new StringBuilder("Java is high level language! Java is cool.");

                    int x;

                    int y;



                    //Using indexOf method for substring

                     x = sbindOf.indexOf("Java");

                     y = sbindOf.indexOf("Java", 10);

                 

                     System.out.println("The index of 'Java' from beginning: " + x +"\n");

                     System.out.println("The occurrence of 'Java' from index 10: " +y);



        }

}

The output:

The index of ‘Java’ from beginning: 0

 

The occurrence of ‘Java’ from index 10: 29

You saw the word ‘Java’ is used twice in the specified string. In the first way of using indexOf method, it returned the 0 index position.

As we specified the fromIndex as 10, the method returned the second occurrence which is 29 in the string.

Example of using lastIndexOf method

Just like the indexOf method, the lastIndexOf method is available for both StringBuilder and StringBuffer classes. The lastIndexOf returns the last occurrence (rightmost) of the given str in the specified string.

You may also specify the index position just like the indexOf method.

See the example below for using this method with StringBuilder class:

          public static void main(String args[]) {

                

                 StringBuilder sbindOf = new StringBuilder("Java is high level language! Java is cool. Java is Awesome.");

                    int x;

                    int y;



                    //Using indexOf method for substring

                     x = sbindOf.lastIndexOf("Java");

                     y = sbindOf.lastIndexOf("Java", 40);

                 

                     System.out.println("The lastIndexOf 'Java' from right most: " + x +"\n");

                     System.out.println("The lastIndexOf of 'Java' from index 40: " +y);



        }

}

The Output:

The lastIndexOf ‘Java’ from right most: 43

 

The lastIndexOf of ‘Java’ from index 40: 29

How to use the length method of StringBuilder/StringBuffer classes?

The length method returns the length or total count of the characters in the specified string. The syntax of using the length method is:

int str.length()

The example below shows using the length method:

public class string_b {

          public static void main(String args[]) {

                 StringBuilder sbLen = new StringBuilder("A demo string for length.");

              System.out.println("The length of string is: " +sbLen.length() );



              sbLen.append("Add few more chars");

              System.out.println("After append, length is:  " +sbLen.length() );

        }

}

The output:

The length of string is: 25

After append, length is:  43

Summarizing the StringBuilder and StringBuffer classes

Both these classes enable us to create mutable strings in Java. If you require lots of modifications in string then the better way is to use either of these classes rather than the String class which is immutable.

As for deciding between StringBuilder vs StringBuffer class, it depends on the thread-safety/synchronization scenario.

If thread-safety is important for the project then use the StringBuffer class. Otherwise, you should use StringBuilder class which is faster.

Both of these classes, otherwise, are almost the same as far as methods and string operations are concerned.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!