Skip to main content

Java StringBuffer

Introduction to Java StringBuffer

Java StringBuffer is a peer class of String that provides much of the functionality of strings. Unlike strings, however, Java StringBuffer is mutable which means it can change over time. This makes the StringBuffer class particularly useful when dealing with strings in Java that need to be modified.

Java StringBuffer Class

The Java StringBuffer class is a part of the java.lang package. It is used to create mutable (modifiable) string objects. This means that the string objects created by the StringBuffer class in Java can be modified over time.

A StringBuffer is like a String but can be modified. It can be compared to a String, but it is growable and modifiable. It is available since JDK 1.0.

The Java StringBuffer class is thread-safe, meaning it is safe to use in multi-threaded environments because two threads can't call the methods of StringBuffer simultaneously.

Creating a StringBuffer

Creating a StringBuffer is similar to creating a regular string. Here is an example:

StringBuffer sb = new StringBuffer("Hello");

In this example, a new StringBuffer object sb is created with the value "Hello".

Java StringBuffer Methods

The StringBuffer class in Java has several methods to manipulate and process the string. Here are a few of the most commonly used ones:

append()

This method concatenates the given argument with the string. Here is an example:

StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // prints "Hello World"

insert()

This method inserts the given string with this string at the given position. Here is an example:

StringBuffer sb = new StringBuffer("Hello World");
sb.insert(5, " Java");
System.out.println(sb); // prints "Hello Java World"

replace()

This method replaces the given string from the specified beginIndex and endIndex. Here is an example:

StringBuffer sb = new StringBuffer("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb); // prints "Hello Java"

delete()

This method removes the string between the specified beginIndex and endIndex. Here is an example:

StringBuffer sb = new StringBuffer("Hello World");
sb.delete(6, 11);
System.out.println(sb); // prints "Hello "

reverse()

This method reverses the current string. Here is an example:

StringBuffer sb = new StringBuffer("Hello World");
sb.reverse();
System.out.println(sb); // prints "dlroW olleH"

These are just a few of the many methods provided by the Java StringBuffer class. You can always check the official Java documentation to explore more methods.

Conclusion

To wrap up, the StringBuffer class in Java is a very useful class when dealing with strings that need to be altered or modified. It's an efficient way of performing string manipulations, and because it's thread-safe, it's also a safer choice in multi-threaded environments.