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
replacemethod is used to replace a substring of the original string with a new value. - Reversal: The
reversemethod is used to reverse the characters in the string. - Appending: The
appendmethod is used to add a string at the end of the original string. - Insertion: The
insertmethod is used to insert a string at a specified position in the original string. - Substring Extraction: The
substringmethod is used to extract a substring from the original string. - Trimming Capacity: The
trimToSizemethod is used to reduce the capacity of theStringBuilderto match its length. - Deletion: The
deletemethod 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
replacemethod is used to replace a substring of the original string with a new value. - Reversal: The
reversemethod is used to reverse the characters in the string. - Appending: The
appendmethod is used to add a string at the end of the original string. - Insertion: The
insertmethod is used to insert a string at a specified position in the original string. - Substring Extraction: The
substringmethod is used to extract a substring from the original string. - Deletion: The
deletemethod is used to remove a substring from the original string. - Trimming Capacity: The
trimToSizemethod is used to reduce the capacity of theStringBufferto 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