This program demonstrates several operations that can be performed using the StringBuffer class. It creates a new StringBuffer object with the initial value "Hello, ", and then appends "world!" to the end of the string using the append() method. It then inserts "Java " into the middle of the string using the insert() method, replaces "Hello" with "Hi" using the replace() method, deletes the first three characters of the string using the delete() method, and reverses the order of the characters in the string using the reverse() method.
public class StringBufferDemo { public static void main(String[] args) { // Create a new StringBuffer object StringBuffer sb = new StringBuffer("Hello, "); // Append a string to the StringBuffer sb.append("world!"); System.out.println(sb); // Insert a string into the middle of the StringBuffer sb.insert(7, "Java "); System.out.println(sb); // Replace a substring within the StringBuffer sb.replace(0, 5, "Hi"); System.out.println(sb); // Delete a portion of the StringBuffer sb.delete(0, 3); System.out.println(sb); // Reverse the StringBuffer sb.reverse(); System.out.println(sb); } }
The output of the program will be:
Hello, world! Hello, Java world! Hi, Java world! Java world! !dlrow avaJ
Comments
Post a Comment