String objects created with Java String class are immutable. It means that String objects do not allow the stored string values to be modified. Class StringBuffer in Java helps when a program needs to allow string values to be modified at the runtime.
String objects declared with StringBuffer in Java allow a user to
- Insert characters in a string
- Delete characters from a string
- Append characters at the end of a string
- Reverse a string
- Set Length of a string
- Find a character at a given position
- Replace some characters in a string
Creating String StringBuffer in Java
The class used for creating and manipulation of StringBuffer objects in Java is the java.lang.StringBuffer class. There are four constructors used to create a StringBuffer object.
Let us have a look at the program that shows these ways of String creation with StringBuffer in Java.
public class StrBufDemo { public static void main (String args[]) { StringBuffer emptyStr=new StringBuffer(); StringBuffer fixedLenStr=new StringBuffer(20); StringBuffer initStr=new StringBuffer("Hello String"); CharSequence chSeq="StringBuffer with Charater Sequence"; StringBuffer charSeqStr=new StringBuffer(chSeq); System.out.println("Length of Empty StringBuffer Object="+emptyStr.length()); System.out.println("Length of Fixed Length StringBuffer Object="+fixedLenStr.length()); System.out.println("Length of Initialised string StringBuffer Object="+initStr.length()); System.out.println("Length of Character Sequence StringBuffer Object="+charSeqStr.length()); } }
StringBuffer Class methods
Many StringBuffer Class methods are available to perform different operations on the strings. Let us understand the use of a few commonly used methods of the StringBuffer Class.
append
This method is used when a string, sequence of characters or the string representation of number, object or Boolean has to be added at the end of an existing StringBuffer object.
Capacity
This method returns the count of characters reserved in a StringBuffer Object.
insert
This method is used to insert a string, sequence of characters or the string representation of number, object or Boolean at a specific position in a StringBuffer object.
charAt
This method returns the character at a given index of the StringBuffer Object.
delete
delete method is used to delete characters in a predefined StringBuffer object. The method needs the start index and the end index.
setLength
setLength method of StringBuffer Object is used to set the length of the sequence of characters.
reverse
reverse method returns the reversed characters stored as a StringBuffer Object.
length
This method returns the length or the number of characters of a StringBuffer Object