STRING BUFFER CLASS
Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.
What is mutable string?
A string that can be modified or changed is known as mutable string.
Syntax
StringBuffer objectname=new StringBuffer();
This allocates an empty space in the memory to store a String.
Example
StringBuffer sb=new StringBuffer(“Sacred Heart School”);
The above statement allocated memory for variable m and initialize it with String “Sacred Heart School”.
Setting String Buffer
StringBuffer m=new StringBuffer(25);
This statement shown above allocates memory space for String with 25 characters.
String Buffer Functions
•append()
•setCharAt()
•Insert()
•delete()
•setLength()
•reverse()
.append()
This function is used to add a string at the end of another string.
Syntax:
Object1.append(object2);
Eg.
StringBuffer m=new StringBuffer(“Sacred”);
StringBuffer n=new StringBuffer(“Heart”);
System.out.println(m.append(n));
Output:
SacredHeart
.setCharAt()
This function can be applied to replace a character with another character at specified location / index.
Syntax:
Object.setCharAt(index, character);
Eg.
StringBuffer m=new StringBuffer(“Sccred”);
System.out.println(m.setCharAt(1, ‘a’));
Output:
Sacred.
.insert()
This function allows us to insert a string at specified location / index into another string.
Syntax:
Object.insert(index, StringBuffer object);
Eg.
StringBuffer m=new StringBuffer(“Sacred School”);
StringBuffer n= new StringBuffer(“ Heart ”);
System.out.println(m.insert(6,n));
Output:
Sacred Heart School.
.delete()
This function is applied to delete the characters from one index to another index in a given string.
Syntax:
Object.delete(sp, ep);
Eg.
StringBuffer m=new StringBuffer(“Sacred Heart School”);
System.out.println(m.delete(6,12));
Output:
SacredSchool.
.replace()
The replace() method replaces the given string from the specified begin Index and end Index.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
.reverse()
The reverse() method of StringBuilder class reverses the current string.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Difference between String and StringBuffer
String
1)String class is immutable.
2)String is slow and consumes more memory when you concat too many strings because every time it creates new instance.
StringBuffer
1) StringBuffer class is mutable.
2) StringBuffer is fast and consumes less memory when you cancat strings.