StringBuffer

StringBuffer class in java is used to create thread safe mutable string.

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.

StringBuffer is also thread safe as all the methods inside this class are synchronized.

Hence multiple threads can’t access it simultaneously.


Following are the available constructors of StringBuffer class


StringBuffer()

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

StringBuffer(CharSequence seq)

Constructs a string buffer that contains the same characters as the specified CharSequence.

StringBuffer(int capacity)

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

StringBuffer(String str)

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


Important methods of StringBuffer class

append()

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

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

We will see only one method which takes String as argument

Method signature

1
public StringBuffer append(String str)
public StringBuffer append(String str)


Example

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



We can see that “sb” object of StringBuffer 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 StringBuffer 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
2
3
4
5
6
7
8
9
public class StringConcat{  
public static void main(String args[]){  
String s="java ";  
s.concat("in ");
s.concat("simple ");
s.concat("way ");
System.out.println(s);
}  
}
public 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.

Check String Immutability article for complete example with explanation of String immutability.

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 StringBuffer insert(int offset, String str)
public StringBuffer insert(int offset, String str)


Example

1
2
3
4
5
6
7
public class StringBufferInsert{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("ja in simple way");  
sb.insert(2,"va"); 
System.out.println(sb);
}  
}  
public class StringBufferInsert{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("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 StringBuffer replace(int start,int end, String str)
public StringBuffer replace(int start,int end, String str)


Example

1
2
3
4
5
6
7
public class StringBufferReplace{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("java in easy way");  
sb.replace(8,12,"simple");  
System.out.println(sb);
}  
}  
public class StringBufferReplace{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("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 StringBuffer object.

Method signature

1
public StringBuffer reverse()
public StringBuffer reverse()


Example

1
2
3
4
5
6
7
public class StringBufferReverse{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("java");  
sb.reverse();  
System.out.println(sb);
} 
}
public class StringBufferReverse{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("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 StringBuffer delete(int start,int end)
public StringBuffer delete(int start,int end)


Example

1
2
3
4
5
6
7
public class StringBufferDelete  {
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("java in very simple way");  
sb.delete(8,12);  
System.out.println(sb);
}  
}
public class StringBufferDelete  {
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("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
2
3
4
5
6
public class StringBufferLength {
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("java in very simple way");    
System.out.println(sb.length());
}  
}
public class StringBufferLength {
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("java in very simple way");    
System.out.println(sb.length());
}  
}



capacity()


This method returns the current capacity of StringBuffer object.

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

The default capacity of the StringBuffer 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
2
3
4
5
6
7
8
9
10
public class StringBufferCapacity{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer();  
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  
}  
}  
public class StringBufferCapacity{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer();  
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
2
3
4
5
6
7
8
public class StringBufferEnsureCapacity {  
public static void main(String args[]){  
StringBuffer sb= new StringBuffer();
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
}  
}  
public class StringBufferEnsureCapacity {  
public static void main(String args[]){  
StringBuffer sb= new StringBuffer();
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