String Buffer
With the help of String Class we can create a string object that is immutable, i.e. its state cannot be
changed. However, StringBuffer class is used to create a mutable string object i.e its state can
be changed after it is created. It represents growable and writable character sequence.
Following program demonstrates the concept.
class Test {
public static void main(String args[])
{
String str = "study";
[Link]("tonight");
[Link](str); // Output: study
StringBuffer strB = new StringBuffer("study");
[Link]("tonight");
[Link](strB); // Output: studytonight
}
}
So StringBuffer class is used when we have to make lot of modifications to our string. It is
also thread safe i.e multiple threads cannot access it simultaneously. StringBuffer defines 4
constructors. They are,
1. StringBuffer ( )
2. StringBuffer ( int size )
3. StringBuffer ( String str )
4. StringBuffer ( charSequence [ ]ch )
Important methods of StringBuffer class
append()
This method will concatenate the string representation of any type of data to the end of the
invoking StringBuffer object. append() method has several overloaded forms.
StringBuffer append(String str)
StringBuffer append(int n)
StringBuffer append(Object obj)
The string representation of each parameter is appended to StringBuffer object.
StringBuffer str = new StringBuffer("test");
[Link](123);
[Link](str);
output : test123
insert()
This method inserts one string into another. Here are few forms of insert() method.
StringBuffer insert(int index, String str)
StringBuffer insert(int index, int num)
StringBuffer insert(int index, Object obj)
Here the first parameter gives the index at which position the string will be inserted and string
representation of second parameter is inserted into StringBuffer object.
StringBuffer str = new StringBuffer("test");
[Link](4, 123);
[Link](str);
output: test123
reverse()
This method reverses the characters within a StringBuffer object.
StringBuffer str = new StringBuffer("Hello");
[Link]();
[Link](str);
output: olleH
replace()
This method replaces the string from specified start index to the end index.
StringBuffer str = new StringBuffer("Hello World");
[Link]( 6, 11, "java");
[Link](str);
Hello java
capacity()
This method returns the current capacity of StringBuffer object.
StringBuffer str = new StringBuffer();
[Link]( [Link]() );
Output: 16
Empty constructor reserves space for 16 characters. Therefore the output is 16.
equals(object)
public boolean equals(Object obj)
returns Boolean value true/false, Indicates whether some other object is "equal to" the
invoking object.
e.g. [Link](ob), tests str and ob for equality.