OCA Java SE 8 Core Java APIs - Java StringBuilder








The StringBuilder class creates a String without storing all those interim String values.

Unlike the String class, StringBuilder is not immutable.

Creating a StringBuilder

There are three ways to construct a StringBuilder:

StringBuilder sb1 = new StringBuilder(); 
StringBuilder sb2 = new StringBuilder("java2s.com"); 
StringBuilder sb3 = new StringBuilder(10); 

The first constructor creates a StringBuilder containing an empty sequence of characters and assign sb1 to point to it.

The second constructor creates a StringBuilder containing a specific value and assign sb2 to point to it.

The third constructor reserves a certain number of slots for characters.





Size vs. Capacity

Size is the number of characters currently in the StringBuilder, and capacity is the number of characters the StringBuilder can currently hold.

For StringBuilder, Java knows the size is likely to change as the object is used.

When StringBuilder is created, it may start at the default capacity of 16 characters or one of the programmer's choosing.

In the following example, we request a capacity of 5. At this point, the size is 0 since no characters have been added yet, but we have space for 5.

Next we add four characters. At this point, the size is 4 since four slots are taken. The capacity is still 5. Then we add three more characters. The size is now 7 since we have used up seven slots. Because the capacity wasn't large enough to store seven characters, Java automatically increased it for us.

StringBuilder sb = new StringBuilder(5); 

0      1       2      3      4 

sb.append("java"); 

j      a       v     a 

0      1       2      3      4 

sb.append("2s.com"); 

j      a       v     a       2       s     .      c      o      m

0      1       2      3      4      5      6      7      ...




charAt(), indexOf(), length(), and substring()

These four methods work exactly the same as in the String class.

public class Main{
   public static void main(String[] argv){
        StringBuilder sb = new StringBuilder("java2s.com"); 
        String sub = sb.substring(sb.indexOf("a"), sb.indexOf("om")); 
        int len = sb.length(); 
        char ch = sb.charAt(6); 
        System.out.println(sub + " " + len + " " + ch); 
   }
}

substring() returns a String rather than a StringBuilder.

That is why sb is not changed.

The code above generates the following result.

append()

append() method adds the parameter to the StringBuilder and returns a reference to the current StringBuilder.

One of the method signatures is as follows:

StringBuilder append(String str) 

There are more than 10 method signatures that look similar but that take different data types as parameters.

All those methods are provided so you can write code like this:

StringBuilder sb = new StringBuilder().append(1).append('c'); 
sb.append("-").append(true); 
System.out.println(sb);      // 1c-true 

insert()

The insert() method adds characters to the StringBuilder at the requested index and returns a reference to the current StringBuilder.

There are lots of method signatures for different types. Here's one:

StringBuilder insert(int offset, String str)

The offset is the index where we want to insert the requested parameter.

public class Main{
   public static void main(String[] argv){
        StringBuilder sb = new StringBuilder("java2s.com");
        sb.insert(7, "-");                   
        sb.insert(0, "-");                   
        sb.insert(4, "-");                   
        System.out.println(sb); 
   }
}

delete() and deleteCharAt()

delete() method is the opposite of the insert() method. delete() method removes characters from the StringBuilder and returns a reference to the current StringBuilder.

The deleteCharAt() method is convenient when you want to delete only one character.

The method signatures are as follows:

StringBuilder delete(int start, int end) 
StringBuilder deleteCharAt(int index) 

The following code shows how to use these methods:

StringBuilder sb = new StringBuilder("abcdef"); 
sb.delete(1, 3);                  // sb = adef 
sb.deleteCharAt(5);               // throws an exception since there is not letter in position 5. 

reverse()

The reverse() method reverses the characters in the sequences and returns a reference to the current StringBuilder.

The method signature is as follows:

StringBuilder reverse() 

The following code shows how to use this method:

public class Main{
   public static void main(String[] argv){
        StringBuilder sb = new StringBuilder("ABC"); 
        sb.reverse(); 
        System.out.println(sb); 
   }
}

The code above generates the following result.

toString()

toString() method converts a StringBuilder into a String.

The method signature is as follows:

String toString() 

The following code shows how to use this method:

String s = sb.toString();