This is a Java code example that demonstrates the usage of StringBuffer
and StringBuilder
classes for manipulating strings.
The code showcases how to use StringBuilder
and StringBuffer
to perform various string operations, such as replacement, reversal, appending, inserting, deletion, and substring extraction.
The example starts by using the StringBuilder
class, which provides a mutable sequence of characters. It shows the following operations:
- Replacement: The
replace
method is used to replace a substring of the original string with a new value. - Reversal: The
reverse
method is used to reverse the characters in the string. - Appending: The
append
method is used to add a string at the end of the original string. - Insertion: The
insert
method is used to insert a string at a specified position in the original string. - Substring Extraction: The
substring
method is used to extract a substring from the original string. - Trimming Capacity: The
trimToSize
method is used to reduce the capacity of theStringBuilder
to match its length. - Deletion: The
delete
method is used to remove a substring from the original string.
The example then demonstrates similar operations using the StringBuffer
class, which is also a mutable sequence of characters. The operations performed include:
- Replacement: The
replace
method is used to replace a substring of the original string with a new value. - Reversal: The
reverse
method is used to reverse the characters in the string. - Appending: The
append
method is used to add a string at the end of the original string. - Insertion: The
insert
method is used to insert a string at a specified position in the original string. - Substring Extraction: The
substring
method is used to extract a substring from the original string. - Deletion: The
delete
method is used to remove a substring from the original string. - Trimming Capacity: The
trimToSize
method is used to reduce the capacity of theStringBuffer
to match its length.
To run the code, follow these steps:
-
Make sure you have Java installed on your system.
-
Copy the code into a Java file (e.g.,
StringBufferStringBuilder.java
). -
Open a terminal or command prompt and navigate to the directory containing the Java file.
-
Compile the code by executing the following command:
javac StringBufferStringBuilder.java