How to use StringBuilder in Java

How to use StringBuilder in Java

Hello everyone, in this article we are going to talk about StringBuilder classes in Java language. We are going to talk about the specifications one by one on examples.

Let's get started.

StringBuilder is a class which allows to build specific and modifable strings in Java.It is similar to String class and StringBuffer class. All of them dedicated to create some mutable sequence of characters.

StringBuffer classes works synchoronised but StringBuilder does not. So if you are need the synchoronisation you need to use StringBuffer instead of StringBuilder.

There are four type constructor of StringBuilder :

  • StringBuilder() Initialize a StringBuilder with no character and with 16 default character capacity.
  • StringBuilder(String str) Initialize a StringBuilder with a specified string.
  • StringBuilder(int lenght) Initialize a StringBuilder with no character and specified char capacity.
  • StringBuilder(CharSequence cs) Initialize a String Builder with specified CharSequence.

Below example you can see the usages of constructors of StringBuilder:

    public void stringBuilderConstructors(){
        StringBuilder sb = new StringBuilder();
        StringBuilder sb1 = new StringBuilder("Thecodeprogram String");
        StringBuilder sb2 = new StringBuilder(10);
        StringBuilder sb3 = new StringBuilder(cs);
    CharSequence cs = new CharSequence() {

After initialization we are going to use the StringBuilder methods. Below you can find the most commonly methods of StringBuilder class.


StringBuilder append(X x)

This Method inserts a text to ending of specified string. This method also overloaded with String, char, boolean int... parameter types. X is the identifier, x parameter.

StringBuilder sb= new StringBuilder("TheCodeProgram");
sb.append(" is the best :). Since : ");
sb.append(" Yes it is ");
Example Output :

TheCodeProgram is the best :). Since : 2015 Yes it is true

StringBuilder insert(int offset, String s)

This method is inserts a text at specified location. We specify the location with offset parameter for this method. This method also averloaded with different types of text parameters like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double).

StringBuilder sb= new StringBuilder("TheCodeProgram");
sb.insert(3, " great ");
sb.insert(0, "Number ");
sb.insert(7, " one, ");
Example Output

The great CodeProgram
Number  one, The great CodeProgram

StringBuilder reverse()

This method reverse the given string within StringBuilder.

StringBuilder sb= new StringBuilder("TheCodeProgram");
Example Output:


int capacity()

This method return capacity of the StringBuilder. If you did not specialized the capacity during initialisation it will return the current capacity value .

StringBuilder sb= new StringBuilder("TheCodeProgram"); // It return current capacity not 14.
System.out.println("First Text Capacity : " + sb.capacity() );
sb.append(" - Burak Hamdi TUFAN");
System.out.println("Second Text Capacity : " + sb.capacity() );
Example Output

First Text Capacity : 30
Second Text Capacity : 62

int length()

This method returns the character count of text within StringBuilder.

StringBuilder sb= new StringBuilder("TheCodeProgram");
System.out.println("First Text Lenght : " + sb.length());
sb.append(" - Burak Hamdi TUFAN");
System.out.println("Second Text Lenght : " + sb.length() );
Example Output

First Text Lenght : 14
Second Text Lenght : 34

String substring(int beginIndex)

This method return the substring text from specified index. This method also overloaded with endindex value. If we send parameter with end index it will return between them.

StringBuilder sb= new StringBuilder("TheCodeProgram");
System.out.println("First Substring : " + sb.substring(3));
System.out.println("Second Substring : " + sb.substring(3, 7));
Example Output:

First Substring : CodeProgram
Second Substring : Code

char charAt(int index)

This method returns the character at the index which we specified.

StringBuilder sb= new StringBuilder("TheCodeProgram");
System.out.println("Forth Char : " + sb.charAt(3));
System.out.println("Eighth Char : " + sb.charAt(7));
Example Output:

Third Char : C
Seventh Char : P

StringBuilder delete(int startIndex, int endIndex) and deleteCharAt(int index)

This methods accomodate the deleting something from text. With delete method: we delete a text between two indexes and also if we want to delete just a character we use deleteCharAt method.

//Delete specified character
StringBuilder sb= new StringBuilder("TheCodeProgram");
//Delete characters between two indexes
sb= new StringBuilder("TheCodeProgram");
sb.delete(3, 7);
//Delete Last n characters
sb= new StringBuilder("TheCodeProgram");
sb.delete(sb.toString().length() - 7, sb.toString().length());
Example Output :


StringBuilder replace(int startIndex, int endIndex, String str)

This method replaces the string with given string between two indexes. If we want to apply this replacement we can give indexes as 0 and StringBulder.lenght.

//Replace text between indexes
StringBuilder sb= new StringBuilder("TheCodeProgram");
sb.replace(3, 7, "XXXX");
//Replace the entire text
sb= new StringBuilder("TheCodeProgram");
sb.replace(0, sb.length(), "BurakHamdiTUFAN");
Example Output:


We can also make specified String replacemetn with an external method like below:

public void replaceSpecifiedString(StringBuilder sb, String findString, String replaceString){
        while(sb.indexOf(findString) > 0){
             sb.replace(sb.indexOf(findString), sb.indexOf(findString) + findString.length(), replaceString);
All we need to call above method like below:

String findString = "Code";
String replaceString = "Burak";
StringBuilder sb= new StringBuilder("TheCodeProgramCodeCodeProgram");
//Calling the method
replaceSpecifiedString(sb, findString,replaceString);
Example Output:


That is all in this article.

Have a good String Building.

I wish you all healthy days.

Burak Hamdi TUFAN.


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment.


    There is no comment. Be the owner of first comment...