StringBuffer class in Java
In this tutorial, we are going to discuss a Java class known as StringBuffer that is much similar to String class. There are many functions in StringBuffer that are similar to the functions of String class and also StringBuffer provides some additional functionalities that are not provided by String class. StringBuffer provides the functionality to add character or substring in the middle of the String or append at the end.
StringBuffer can create mutable string. Mutable string is a string that can be changed or modified.
Methods of StringBuffer class
Here we will discuss some important methods of StringBuffer class in Java.
insert function is used to insert string at the given position.
StringBuffer sb = new StringBuffer("Codespeedy "); sb.insert(4,"Java");//now original string is changed System.out.println(sb); /*prints "CodeJavaspeedy "*/
insert the string at the end of the given string.
StringBuffer sb=new StringBuffer("Code"); sb.append("speedy"); /* concatenation of "speedy" with the original string*/ System.out.println(sb);//prints Codespeedy
This function is used to replace the character at a given position with the other character.
StringBuffer sb=new StringBuffer("Code"); sb.replace(1,4,"speedy"); System.out.println(sb);//prints Cspeedy
This function deletes the string from a beginning index to an end index.
StringBuffer sb=new StringBuffer("Codespeedy"); sb.delete(1,4); System.out.println(sb);//prints Cdepeedy
This function is used to reverse the string.
StringBuffer sb=new StringBuffer("Codespeedy"); sb.reverse(); System.out.println(sb);//prints ydeepsedoC
This method returns the capacity of the String. The default capacity of StringBuffer is 16.
StringBuffer sb=new StringBuffer(); sb.append("Codespeedy"); System.out.println(sb.capacity());//prints 16
Constructors used in StringBuffer
- StringBuffer(): This constructor is used to create a string of capacity 16.
- StringBuffer(String string): This constructor creates a buffer with the specified string.
- StringBuffer(int capacity): This constructor creates a string with custom capacity.
Some important facts about StringBuffer :
- StringBuffer is like the String class.
- StringBuffer has existing methods to modify length and memory allocations whereas these properties are final in String class.
- Methods of StringBuffer are synchronized which is why object of StringBuffer can not be used by multiple threads at the same time.
- StringBuffer class inherits inherits clone(), finalize(), getClass(), equals(), hashCode(), notify(), notifyAll() from the Object superclass.
- CharSequence and Appendable interfaces are implemented by the StringBuffer class.
- StringBuffer operates slower due to synchronization in comparison to other String classes like StringBuilder.
Hence, StringBuffer is used to create String objects that can be modified. So StringBuffer can be used to reverse, replace, concatenate, append strings.
Hope you like the content.