What is a StringBuffer in Java?
StringBuffer is a type of object in Java used to create and manipulate strings of text. Unlike regular strings in Java (which are immutable, meaning they can't be changed once created), a StringBuffer can be modified after it is created.
JAVA PROGRAMMING
Why Use StringBuffer?
• Efficiency: If you're going to make a lot of changes to a string, StringBuffer is faster and uses less memory than regular strings.
• Flexibility: You can easily add, delete, or change parts of the string without creating new strings each time.
Basic Operations
Here are some simple things you can do with a StringBuffer:
1. Create a StringBuffer:
StringBuffer sb = new StringBuffer("Hello");
2. Append (add) text:
sb.append(" World");
// Now sb contains "Hello World"
3. Insert text:
sb.insert(5, " Java");
// Now sb contains "Hello Java World"
4. Delete text:
sb.delete(5, 10);
// Now sb contains "Hello World" (removes " Java")
5. Reverse text:
sb.reverse();
// Now sb contains "dlroW olleH"
6. Change text at a specific position:
sb.setCharAt(0, 'h');
// Now sb contains "h World"
Example
Let's put this all together in a small program:
public class Main {
public static void main(String[] args) {
StringBuffer story = new StringBuffer("Once upon a time");
// Adding more to the story
story.append(", in a land far, far away");
// Inserting some details
story.insert(12, " long ago");
// Deleting a redundant part
story.delete(36, 41);
// Reversing the story (just for fun)
story.reverse();
// Printing the story
System.out.println(story.toString()); }
}
When you run this program, you'll see how StringBuffer makes it easy to manipulate the text of the story.
Conclusion
StringBuffer is like a flexible and efficient notebook for your text in Java. It allows you to make changes without creating new strings all the time, making your programs faster and more memory-efficient.