Examples of the above methods
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 and storing string by creating object of
// StringBuffer
StringBuffer s = new StringBuffer("w3wiki");
// 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 w3wiki="
+ p);
System.out.println(
"Capacity of string w3wiki=" + q);
}
}
Output
Length of string w3wiki=13 Capacity of string w3wiki=29
Example 2: append()
It is used to add text at the end of the existing text.
Here are a few of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
// 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 w3wiki
System.out.println(s);
s.append(1);
// Returns w3wiki1
System.out.println(s);
}
}
Output
w3wiki w3wiki1
Example 3: insert()
It is used to insert text at the specified index position.
Syntax: These are a few of its as follows:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
Here, the index specifies the index at which point the string will be inserted into the invoking StringBuffer object.
// 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 w3wiki
System.out.println(s);
s.insert(0, 5);
// Returns 5w3wiki
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);
}
}
Output
w3wiki 5w3wiki 5GetrueeksforGeeks 5Getr41.35ueeksforGeeks 5Getr41.41.3535ueeksforGeeks 5Gpawanetr41.41.3535ueeksforGeeks
Example 4: reverse( )
It can reverse the characters within a StringBuffer object using reverse( ). This method returns the reversed object on which it was called.
// 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);
}
}
Output
skeeGskeeG
Example 5: delete( ) and deleteCharAt()
It can delete characters within a StringBuffer by using the methods delete( ) and deleteCharAt( ).The delete( ) method deletes a sequence of characters from the invoking object. Here, the start Index specifies the index of the first character to remove, and the end Index specifies an index one past the last character to remove. Thus, the substring deleted runs from start Index to endIndex–1. The resulting StringBuffer object is returned. The deleteCharAt( ) method deletes the character at the index specified by loc. It returns the resulting StringBuffer object.
Syntax:
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
// 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("w3wiki");
s.delete(0, 5);
// Returns forGeeks
System.out.println(s);
s.deleteCharAt(7);
// Returns forGeek
System.out.println(s);
}
}
Output
forGeeks forGeek
Example 6: replace()
It can replace one set of characters with another set inside a StringBuffer object by calling replace( ). The substring being replaced is specified by the indexes start Index and endIndex. Thus, the substring at start Index through endIndex–1 is replaced. The replacement string is passed in str. The resulting StringBuffer object is returned.
Syntax:
StringBuffer replace(int startIndex, int endIndex, String str)
Example
// 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("w3wiki");
s.replace(5, 8, "are");
// Returns GeeksareGeeks
System.out.println(s);
}
}
Output
GeeksareGeeks
StringBuffer class in Java
StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an alternative to the immutable String class, allowing you to modify the contents of a string without creating a new object every time.
Here are some important features and methods of the StringBuffer class:
- StringBuffer objects are mutable, meaning that you can change the contents of the buffer without creating a new object.
- The initial capacity of a StringBuffer can be specified when it is created, or it can be set later with the ensureCapacity() method.
- The append() method is used to add characters, strings, or other objects to the end of the buffer.
- The insert() method is used to insert characters, strings, or other objects at a specified position in the buffer.
- The delete() method is used to remove characters from the buffer.
- The reverse() method is used to reverse the order of the characters in the buffer.
Here is an example of using StringBuffer to concatenate strings:
public class StringBufferExample {
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer();
sb.append("Hello");
sb.append(" ");
sb.append("world");
String message = sb.toString();
System.out.println(message);
}
}
Output
Hello world
There are several advantages of using StringBuffer over regular String objects in Java:
- Mutable: StringBuffer objects are mutable, which means that you can modify the contents of the object after it has been created. In contrast, String objects are immutable, which means that you cannot change the contents of a String once it has been created.
- Efficient: Because StringBuffer objects are mutable, they are more efficient than creating new String objects each time you need to modify a string. This is especially true if you need to modify a string multiple times, as each modification to a String object creates a new object and discards the old one.
Note: Both String and StringBuffer objects are thread safe.
StringBuffer is synchronized i.e. thread-safe, which means multiple threads can access it simultaneously (they can be safely accessed and modified by multiple threads simultaneously).
Immutable objects are by default thread-safe because their state can not be modified once created. Since String is immutable in Java, it’s inherently thread safe.
Overall, if you need to perform multiple modifications to a string, using StringBuffer can be more efficient than regular String objects.
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.
StringBuffer class is used to create mutable (modifiable) strings. The StringBuffer class in Java is the same as the String class except it is mutable i.e. it can be changed.