StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences. StringBuffer may have characters and substrings inserted in the middle or appended to the end. It will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth.
Do keep the following points in the back of your mind:
Remember: StringBuilder, J2SE 5 adds a new string class to Java’s already powerful string handling capabilities. This new class is called StringBuilder. It is identical to StringBuffer except for one important difference: it is not synchronized, which means that it is not thread-safe. The advantage of StringBuilder is faster performance. However, in cases in which you are using multithreading, you must use StringBuffer rather than StringBuilder.
Constructor | Description |
---|---|
StringBuffer() | It creates an empty String buffer with the initial capacity of 16. |
StringBuffer(String str) | It creates a String buffer with the specified string. |
StringBuffer(int capacity) | It creates an empty String buffer with the specified capacity as length. |
Modifier and Type | Method | Description |
---|---|---|
public synchronized StringBuffer | append(String s) | It is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc. |
public synchronized StringBuffer | insert(int offset, String s) | It is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc. |
public synchronized StringBuffer | replace(int startIndex, int endIndex, String str) | It is used to replace the string from specified startIndex and endIndex. |
public synchronized StringBuffer | delete(int startIndex, int endIndex) | It is used to delete the string from specified startIndex and endIndex. |
public synchronized StringBuffer | delete(int startIndex, int endIndex) | It is used to delete the string from specified startIndex and endIndex. |
public synchronized StringBuffer | reverse() | is used to reverse the string. |
public int | capacity() | It is used to return the current capacity. |
public void | ensureCapacity(int minimumCapacity) | It is used to ensure the capacity at least equal to the given minimum. |
public char | charAt(int index) | It is used to return the character at the specified position. |
public int | length() | It is used to return the length of the string i.e. total number of characters. |
public String | substring(int beginIndex) | It is used to return the substring from the specified beginIndex. |
public String | substring(int beginIndex, int endIndex) | It is used to return the substring from the specified beginIndex and endIndex. |
Below are the most widely used methods.
ensureCapacity(): It is used to increase the capacity of a StringBuffer object. The new capacity will be set to either the value we specify or twice the current capacity plus two (i.e. capacity+2), whichever is larger. Here, capacity specifies the size of the buffer.
Syntax:
void ensureCapacity(int capacity)
appendCodePoint(int codePoint): This method appends the string representation of the codePoint argument to this sequence.
Syntax:
public StringBuffer appendCodePoint(int codePoint)
charAt(int index): This method returns the char value in this sequence at the specified index.
Syntax:
public char charAt(int index)
IntStream chars(): This method returns a stream of int zero-extending the char values from this sequence.
Syntax:
public IntStream chars()
int codePointAt(int index): This method returns the character (Unicode code point) at the specified index.
Syntax:
public int codePointAt(int index)
int codePointBefore(int index): This method returns the character (Unicode code point) before the specified index.
Syntax:
public int codePointBefore(int index)
int codePointCount(int beginIndex, int endIndex): ]This method returns the number of Unicode code points in the specified text range of this sequence.
Syntax:
public int codePointCount(int beginIndex, int endIndex)
IntStream codePoints(): This method returns a stream of code point values from this sequence.
Syntax:
public IntStream codePoints()
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): In this method, the characters are copied from this sequence into the destination character array dst.
Syntax:
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
int indexOf(String str): This method returns the index within this string of the first occurrence of the specified substring.
Syntax:
public int indexOf(String str)
public int indexOf(String str, int fromIndex)
int lastIndexOf(String str): This method returns the index within this string of the last occurrence of the specified substring.
Syntax:
public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)
int offsetByCodePoints(int index, int codePointOffset): This method returns the index within this sequence that is offset from the given index by codePointOffset code points.
Syntax:
public int offsetByCodePoints(int index, int codePointOffset)
void setCharAt(int index, char ch): In this method, the character at the specified index is set to ch.
Syntax:
public void setCharAt(int index, char ch)
void setLength(int newLength): This method sets the length of the character sequence.
Syntax:
public void setLength(int newLength)
CharSequence subSequence(int start, int end): This method returns a new character sequence that is a subsequence of this sequence.
Syntax:
public CharSequence subSequence(int start, int end)
String substring(int start): This method returns a new String that contains a subsequence of characters currently contained in this character sequence.
Syntax:
public String substring(int start)
public String substring(int start,int end)
String toString(): This method returns a string representing the data in this sequence.
Syntax:
public String toString()
void trimToSize(): This method attempts to reduce storage used for the character sequence.
Syntax:
public void trimToSize()
Implementation
Example 1: length() and capacity() Methods
// Java Program to Illustrate StringBuffer class
// via length() and capacity() methods
// Importing I/O classes
import java.io.*;
// Main class
class GFG {
// main driver method
public static void main(String[] args)
{
// Creating adn storing string by creating object of
// StringBuffer
StringBuffer s = new StringBuffer("GeeksforGeeks");
// Getting the length of the string
int p = s.length();
// Getting the capacity of the string
int q = s.capacity();
// Printing the length and capacity of
// above generated input string on console
System.out.println("Length of string GeeksforGeeks="
+ p);
System.out.println(
"Capacity of string GeeksforGeeks=" + q);
}
}
Example 2: append():
// Java Program to Illustrate StringBuffer class
// via append() method
// Importing required classes
import java.io.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an object of StringBuffer class and
// passing random string
StringBuffer s = new StringBuffer("Geeksfor");
// Usage of append() method
s.append("Geeks");
// Returns GeeksforGeeks
System.out.println(s);
s.append(1);
// Returns GeeksforGeeks1
System.out.println(s);
}
}
Example 3: insert():
// Java Program to Illustrate StringBuffer class
// via insert() method
// Importing required I/O classes
import java.io.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an object of StringBuffer class
StringBuffer s = new StringBuffer("GeeksGeeks");
// Inserting element and position as an arguments
s.insert(5, "for");
// Returns GeeksforGeeks
System.out.println(s);
s.insert(0, 5);
// Returns 5GeeksforGeeks
System.out.println(s);
s.insert(3, true);
// Returns 5GetrueeksforGeeks
System.out.println(s);
s.insert(5, 41.35d);
// Returns 5Getr41.35ueeksforGeeks
System.out.println(s);
s.insert(8, 41.35f);
// Returns 5Getr41.41.3535ueeksforGeeks
System.out.println(s);
// Declaring and initializing character array
char geeks_arr[] = { 'p', 'a', 'w', 'a', 'n' };
// Inserting character array at offset 9
s.insert(2, geeks_arr);
// Returns 5Gpawanetr41.41.3535ueeksforGeeks
System.out.println(s);
}
}
Example 4: reverse():
// Java Program to Illustrate StringBuffer class
// via reverse() method
// Importing I/O classes
import java.io.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating a string via creating
// object of StringBuffer class
StringBuffer s = new StringBuffer("GeeksGeeks");
// Invoking reverse() method
s.reverse();
// Returns "skeeGrofskeeG"
System.out.println(s);
}
}
Example 5: delete() and deleteCharAt()
// Java Program to Illustrate StringBuffer class
// via delete() and deleteCharAt() Methods
// Importing I/O classes
import java.io.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("GeeksforGeeks");
s.delete(0, 5);
// Returns forGeeks
System.out.println(s);
s.deleteCharAt(7);
// Returns forGeek
System.out.println(s);
}
}
Example 6: replace()
// Java Program to Illustrate StringBuffer class
// via replace() method
// Importing I/O classes
import java.io.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("GeeksforGeeks");
s.replace(5, 8, "are");
// Returns GeeksareGeeks
System.out.println(s);
}
}