StringBuilder

StringBuilder is very similar to StringBuffer except for one important difference which is not synchronized.

It means StringBuilder is not thread safe as methods inside StringBuilder class are not synchronised.

StringBuilder is also mutable like StringBuffer.


Mutable string means we can modify the string as many times as we want without creating a new string for each modification.

This way we can save lot of memory.

We know that String is immutable, when we do lot of modification to string object then we will end up with huge memory leakage.

Because of this, we should avoid using String if there is a frequent modification required.

Following are the available constructors of StringBuilder class


StringBuilder()

Constructs a StringBuilder with no characters in it and an initial capacity of 16 characters.

StringBuilder(CharSequence seq)

Constructs a StringBuilder that contains the same characters as the specified CharSequence.

StringBuilder(int capacity)

Constructs a StringBuilder with no characters in it and the specified initial capacity.

StringBuilder(String str)

Constructs a StringBuilder initialized to the contents of the specified string.


Important methods of StringBuilder class

append()

This method concatenates or append the given string to the end of invoking object.

There are various overload append() methods defined in StringBuilder class

We will see only one method which takes String as argument

Method signature

  1. public StringBuilder append(String str)
public StringBuilder append(String str)


Example

  1. public class StringBuilderAppend{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("java ");  
  4. sb.append("in ");
  5. sb.append("simple ");
  6. sb.append("way ");
  7. System.out.println(sb);
  8. }  
  9. }
public class StringBuilderAppend{  
public static void main(String args[]){  
StringBuilder sb=new StringBuilder("java ");  
sb.append("in ");
sb.append("simple ");
sb.append("way ");
System.out.println(sb);
}  
}



We can see that “sb” object of StringBuilder is getting modified for each append operation and hence at the end we got appended result when we print “sb”

This is the best advantage of StringBuilder class in terms of saving memory for frequent modification.

If we run the same program using String,we can see the output as below

  1. class StringConcat{  
  2. public static void main(String args[]){  
  3. String s="java ";  
  4. s.concat("in ");
  5. s.concat("simple ");
  6. s.concat("way ");
  7. System.out.println(s);
  8. }  
  9. }
class StringConcat{  
public static void main(String args[]){  
String s="java ";  
s.concat("in ");
s.concat("simple ");
s.concat("way ");
System.out.println(s);
}  
}



This is because string is immutable and hence any modification will create new string in the memory.


insert()

This method inserts the given string to the string object which is invoking it

There are various overloaded methods for insert()

We will see one of them

Method signature

  1. public StringBuilder insert(int offset, String str)
public StringBuilder insert(int offset, String str)


Example

  1. public class StringBuilderInsert{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("ja in simple way");  
  4. sb.insert(2,"va");
  5. System.out.println(sb);
  6. }  
  7. }  
public class StringBuilderInsert{  
public static void main(String args[]){  
StringBuilder sb=new StringBuilder("ja in simple way");  
sb.insert(2,"va"); 
System.out.println(sb);
}  
}  



We can observe in output that, string “va” is inserted at position “2” of original string

replace()

This method replaces the string from specified start index to the specified end index -1.

Method signature

  1. public StringBuilder replace(int start,int end, String str)
public StringBuilder replace(int start,int end, String str)


Example

  1. public class StringBuilderReplace{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("java in easy way");  
  4. sb.replace(8,12,"simple");  
  5. System.out.println(sb);
  6. }  
  7. }  
public class StringBuilderReplace{  
public static void main(String args[]){  
StringBuilder sb=new StringBuilder("java in easy way");  
sb.replace(8,12,"simple");  
System.out.println(sb);
}  
}  



We can observe in the output that in original string, substring starting from index 8 to index 12 which is “easy” is replaced by “simple”.


reverse()

This method reverses the characters within a StringBuilder object.

Method signature

  1. public StringBuilder reverse()
public StringBuilder reverse()


Example

  1. public class StringBuilderReverse{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("java");  
  4. sb.reverse();  
  5. System.out.println(sb);
  6. }
  7. }
public class StringBuilderReverse{  
public static void main(String args[]){  
StringBuilder sb=new StringBuilder("java");  
sb.reverse();  
System.out.println(sb);
} 
}



delete()

This method deletes the string from the specified begin Index to specified end Index -1.

Method signature

  1. public StringBuilder delete(int start,int end)
public StringBuilder delete(int start,int end)


Example

  1. public class StringBuilderDelete  {
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("java in very simple way");  
  4. sb.delete(8,12);  
  5. System.out.println(sb);
  6. }  
  7. }
public class StringBuilderDelete  {
public static void main(String args[]){  
StringBuilder sb=new StringBuilder("java in very simple way");  
sb.delete(8,12);  
System.out.println(sb);
}  
}



length()

This method returns the length or character count.

Method signature

  1. public int length()
public int length()


Example

  1. public class StringBuilderLength {
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("java in very simple way");    
  4. System.out.println(sb.length());
  5. }  
  6. }
public class StringBuilderLength {
public static void main(String args[]){  
StringBuilder sb=new StringBuilder("java in very simple way");    
System.out.println(sb.length());
}  
}



capacity()


This method returns the current capacity of StringBuilder object.

The capacity is the amount of storage available for newly inserted characters

The default capacity of the StringBuilder object is 16

If the number of character increases from its current capacity then it automatically doubles the capacity and adds extra 2 to it.

  1. newCapacity = (oldCapacity*2) + 2.
newCapacity = (oldCapacity*2) + 2.

Method signature

  1. public int capacity()
public int capacity()


Example

  1. public class StringBuilderCapacity{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder();  
  4. System.out.println(sb.capacity());//default capacity:16  
  5. sb.append("java");  
  6. System.out.println(sb.capacity());//even now capacity:16  
  7. sb.append("java in simple way");  
  8. System.out.println(sb.capacity());//now capacity is doubled  
  9. }  
  10. }  
public class StringBuilderCapacity{  
public static void main(String args[]){  
StringBuilder sb=new StringBuilder();  
System.out.println(sb.capacity());//default capacity:16  
sb.append("java");  
System.out.println(sb.capacity());//even now capacity:16  
sb.append("java in simple way");  
System.out.println(sb.capacity());//now capacity is doubled  
}  
}  



We can observe in the output that, capacity is same when characters are within the initial capacity of 16 and it gets doubled and adds 2 more to initial capacity once number of characters increases beyond initial capacity.

ensureCapacity()


This method is used to ensure that the capacity is at least equal to the specified minimum.

If the argument of the ensureCapacity() method is less than the existing capacity, then there will be no change in existing capacity.

If the argument of the ensureCapacity() method is greater than the existing capacity, then current capacity will be increased as below

  1. newCapacity = (oldCapacity*2) + 2.
newCapacity = (oldCapacity*2) + 2.

Method signature

  1. public void ensureCapacity(int minimumCapacity)
public void ensureCapacity(int minimumCapacity)


Example

  1. public class StringBuilderEnsureCapacity {  
  2. public static void main(String args[]){  
  3. StringBuilder sb= new StringBuilder();
  4. System.out.println(sb.capacity());// default capacity: 16
  5. sb.ensureCapacity(30); //its greater than the existing capacity
  6. System.out.println(sb.capacity()); //new capacity: 34
  7. }  
  8. }  
public class StringBuilderEnsureCapacity {  
public static void main(String args[]){  
StringBuilder sb= new StringBuilder();
System.out.println(sb.capacity());// default capacity: 16
sb.ensureCapacity(30); //its greater than the existing capacity
System.out.println(sb.capacity()); //new capacity: 34
}  
}  


About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on