[post-views]
In this lesson, you will learn
The StringBuffer class in Java is used to create mutable (modifiable) strings. Unlike String immutable objects StringBuffer objects can be modified after they are created.
This makes StringBuffer particularly useful when you need to modify strings of characters.
StringBuffer defines these four constructors
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)
Constructs a string buffer with no characters and an initial capacity of 16 characters.
StringBuffer sb = new StringBuffer();
The default constructor (the one with no parameters) reserves room for 16 characters without reallocation.
Constructs a string buffer with no characters and the specified initial capacity.
StringBuffer sb = new StringBuffer(50);
Constructs a string buffer initialized to the contents of the specified string.
StringBuffer sb = new StringBuffer("Hello");
Sets the initial contents of the StringBuffer object and reserves room for 16 more characters without
reallocation
Constructs a string buffer that contains the same characters as the specified CharSequence.
StringBuffer sb = new StringBuffer("Hello");
Creates an object that contains the character sequence contained in chars and reserves room for 16 more characters.
length() returns the length of the character sequence in the buffer, and capacity() returns the current capacity.
Syntax
int length( )
int capacity( )
StringBuffer sb = new StringBuffer("Hello");
int len = sb.length(); // 5
int cap = sb.capacity(); // 21 (16 default capacity + 5 characters)
Ensures that the capacity is at least equal to the specified minimum.
Syntax
void ensureCapacity(int minCapacity)
StringBuffer sb = new StringBuffer();
sb.ensureCapacity(50);
Sets the length of the character sequence. If the sequence is shortened, characters are lost; if it is extended, null characters are added.
Syntax
StringBuffer sb = new StringBuffer("Hello");
sb.setLength(2);
// sb = "He"
The value of a single character can be obtained from a StringBuffer via the charAt( ) method. You can set the value of a character within a StringBuffer using setCharAt( ).
Syntax
char charAt(int where)
void setCharAt(int where, char ch)
StringBuffer sb = new StringBuffer("Hello World");
char c = sb.charAt(0); // 'H'
sb.setCharAt(0, 'Y'); // "Yello World"
It appends data of various types to the end of the StringBuffer.
Syntax
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
package ch11.l5;
public class StringBufferAppendExample {
public static void main(String[] args) {
// Initialize a StringBuffer with a basic greeting
StringBuffer sb = new StringBuffer("Greeting: ");
// Append various data types
sb.append("Hello, "); // Append a String
sb.append('A'); // Append a char
sb.append(true); // Append a boolean
sb.append(123); // Append an int
sb.append(45.67); // Append a double
char[] arr = {' ', 'W', 'o', 'r', 'l', 'd'};
sb.append(arr); // Append a char array
// Print the final string
System.out.println(sb);
}
}
Output
Greeting: Hello, Atrue12345.67 World
Allowing you to insert data of various types into a specific position within the StringBuffer.
Syntax
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
package ch11.l5;
public class StringBufferInsertExample {
public static void main(String[] args) {
// Create a StringBuffer object
StringBuffer sb = new StringBuffer("0123456789");
// Insert a string at index 4
sb.insert(4, " inserted string ");
// Now sb = "0123 inserted string 456789"
// Insert a character at index 0
sb.insert(0, 'A');
// Now sb = "A0123 inserted string 456789"
// Insert an array of characters at index 10
char[] charArray = {'C', 'h', 'a', 'r', 's'};
sb.insert(10, charArray);
// Now sb = "A0123 inserted Chars string 456789"
// Insert a boolean value at index 5
sb.insert(5, true);
// Now sb = "A0123 true inserted Chars string 456789"
// Insert an integer at index 24
sb.insert(24, 1234);
// Now sb = "A0123 true inserted Chars st1234ring 456789"
// Insert a float value at index 30
sb.insert(30, 5.67f);
// Now sb = "A0123 true inserted Chars st1234ring 5.67456789"
// Display the final result
System.out.println(sb.toString());
}
}
Output
A0123true inseCharsrted 1234st5.67ring 456789
It used to reverse the characters within the StringBuffer itself.
Syntax
StringBuffer reverse( )
public class StringBufferReverseExample {
public static void main(String[] args) {
// Create a StringBuffer with some text
StringBuffer sb = new StringBuffer("Hello World");
// Reverse the StringBuffer contents
sb.reverse();
// Display the reversed string
System.out.println("Reversed string: " + sb.toString());
}
}
Reversed string: dlroW olleH
The delete( ) method deletes a sequence of characters. The substring deleted runs from startIndex to endIndex–1.
Syntax
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
deleteCharAt(int index ): Removes the character at the specified position in this sequence, shifting any subsequent characters to the left.
package ch11.l5;
public class StringBufferDeleteExample {
public static void main(String[] args) {
// Create a StringBuffer with some text
StringBuffer sb = new StringBuffer("This is a test string.");
// Delete a range of characters from index 5 to 10 ("is a")
sb.delete(5, 10);
// Display the string after deletion
System.out.println("After delete: " + sb.toString());
// Output: "This a test string."
// Delete the character at index 0 ('T')
sb.deleteCharAt(0);
// Display the string after deleting character at index 0
System.out.println("After deleteCharAt: " + sb.toString());
// Output: "his a test string."
}
}
Output
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
It is used to replace a sequence of characters in the StringBuffer with another sequence of characters.
Syntax
StringBuffer replace(int startIndex, int endIndex, String str)
package ch11.l5;
public class StringBufferReplaceExample {
public static void main(String[] args) {
// Create a StringBuffer with some text
StringBuffer sb = new StringBuffer("Hello, Java!");
// Replace "Java" with "World"
sb.replace(7, 11, "World");
// Display the updated string
System.out.println(sb.toString()); // Output: "Hello, World!"
}
}
Output
StringBuffer replace(int startIndex, int endIndex, String str)
Syntax
String substring(int startIndex)
String substring(int startIndex, int endIndex)
package ch11.l5;
public class StringBufferSubstringExample {
public static void main(String[] args) {
// Create a StringBuffer with some text
StringBuffer sb = new StringBuffer("Hello, World!");
// Extract substring from index 7 to the end
String str1 = sb.substring(7);
System.out.println("Substring from index 7: " + str1); // Output: "World!"
// Extract substring from index 0 to 5 (exclusive)
String str2 = sb.substring(0, 5);
System.out.println("Substring from index 0 to 5: " + str2); // Output: "Hello"
}
}
Output
Substring from index 7: World!
Substring from index 0 to 5: Hello
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.