Java StringBuilder With Examples

Java StringBuilder class is mutable sequence of characters. StringBuilder Class can be comparable to String however the StringBuilder class provides more versatility because of its modification features.

Java StringBuilder

  • StringBuilder class provides an API similar to StringBuffer, but unlike StringBuffer, it doesn’t guarantee thread safety.
  • Java StringBuilder class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case).
  • If execution speed and performance is a factor, StringBuilder class can be used in place of StringBuffer.
  • The bread-and-butter operations provided by the StringBuilder Class are the append() and insert() methods. These methods are overloaded within StringBuilder in order to accommodate different data type.
  • The general process flow of StringBuilder append and insert methods is: (1) converts a given data to a string then (2) appends or inserts the characters of that string to the string builder. Java StringBuilder append() method always adds these characters at the end of the builder; insert() method inserts character(s) at a specified point.

StringBuilder Class Diagram


StringBuffer and StringBuilder

StringBuffer StringBuilder
Synchronized, hence thread safe. Not synchronized, not thread safe.
Operates slower due to thread safety feature Better performance compared to StringBuffer
Has some extra methods – substring, length, capacity etc. Not needed because these methods are present in String too.
Introduced in Java 1.2 Introduced in Java 1.5 for better performance.

Java StringBuilder Constructors

Constructor Description
StringBuilder() Creates an empty string builder with a default capacity of 16 (16 empty elements).
StringBuilder(CharSequence cs) Constructs a string builder containing the same characters as the specified CharSequence, plus an extra 16 empty elements trailing the CharSequence.
StringBuilder(int initCapacity) Creates an empty string builder with the specified initial capacity.
StringBuilder(String s) Creates a string builder whose value is initialized by the specified string, plus an extra 16 empty elements trailing the string.

StringBuilder Length and Capacity

Java StringBuilder class, much like the String class, has length() method that returns the length of the character sequence in the builder.

However, StringBuilder inherits capacity() method from its superclass AbstractStringBuilder, that returns the number of character spaces that have been allocated. The returned value is always greater than or equal to the length (usually greater than) and automatically expands whenever necessary to accommodate character additions to the string builder.

// creates empty builder, capacity 16
StringBuilder sb = new StringBuilder();
// adds 5 character string at beginning
System.out.println("StringBuilder length = "+sb.length()); // prints 5
System.out.println("StringBuilder capacity = "+sb.capacity()); // prints 16

There are couple of other methods related to StringBuilder length and capacity.

  1. void setLength(int newLength): Sets the length of the character sequence. If newLength is less than length(), the last characters in the character sequence are truncated. If newLength is greater than length(), null characters are added at the end of the character sequence.
  2. void ensureCapacity(int minCapacity): Ensures that the capacity is at least equal to the specified minimum.

StringBuilder methods like append(), insert() or setLength() can increase the length of the character sequence in the string builder so that the returned value of length() would be greater than the current capacity(). In this case, the capacity is automatically increased.

Java StringBuilder Example

Let’s see the examples of different methods of StringBuilder class.

  1. append(): The StringBuilder append() method concatenates or attaches the passed String argument with the existing declared string. It attaches it after the declared string.
    public class StringBuilderExample {
    	public static void main(String[] args) {
    		StringBuilder sb = new StringBuilder("Hello ");
    		sb.append("World");// now original string is changed
    		System.out.println(sb);// prints Hello World

    Output: Hello World

  2. insert(): StringBuilder insert() method inserts the passed String argument at the passed String index.
    StringBuilder sb = new StringBuilder("HellWorld");
    sb.insert(4, "o ");
    System.out.println(sb);// prints Hello World
  3. replace(int startIndex, int endIndex, String str): StringBuilder replace() method replaces the existing declared string. String replacement occurs from the passed startingIndex up to the endingIndex.
    StringBuilder sb = new StringBuilder("Hello World!");
    System.out.println(sb);// prints Hello Earth!
  4. delete(int startIndex, int endIndex): StringBuilder delete() method deletes a character or sets of characters. Deletion occurs at passed startingIndex up to endingIndex.
    StringBuilder sb = new StringBuilder("");
    System.out.println(sb);// prints Journal
  5. reverse(): The reverse() method of StringBuilder class reverses the existing declared string. Invoking a reverse() method on a StringBuilder object with no existing declared value throws NullPointerException.
    StringBuilder sb = new StringBuilder("lived");
    System.out.println(sb);// prints devil
  6. capacity(): The capacity() method of StringBuilder class returns the current capacity of the StringBuilder object. The default capacity of the Builder is 16. If the number of character increases from its current capacity, it increases the capacity by (old_capacity*2)+2 e.g. at current capacity 16, it becomes (16*2)+2=34.
    StringBuilder sb=new StringBuilder();
    System.out.println(sb.capacity()); // default value 16
    System.out.println(sb.capacity()); // still 16
    sb.append("Hello StringBuilder Class!");
    System.out.println(sb.capacity()); // (16*2)+2
  7. ensureCapacity(): The ensureCapacity() method of StringBuilder class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (old_capacity*2)+2 e.g. at current capacity 16, it becomes (16*2)+2 which is 34.
    public class StringBuilderExample {
    	public static void main(String[] args) {
    		StringBuilder sbObj=new StringBuilder();
    		System.out.println(sbObj.capacity());//default 16
    		sbObj.append("Java StringBuilder Class!");
    		System.out.println(sbObj.capacity());// capacity 34
    		sbObj.ensureCapacity(12);// no change
    		System.out.println(sbObj.capacity());//still 34
    		sbObj.ensureCapacity(60); // (34*2)+2 = 70
    		System.out.println(sbObj.capacity()); //70

That’s all for Java StringBuilder class. It’s a very useful class to work with Strings in java.

Reference: API Doc

By admin

Leave a Reply

%d bloggers like this: