Java StringBuffer Class Example

By IncludeHelp Last updated : January 30, 2024

Java StringBuffer Class

Java StringBuffer class is used to create mutable (modifiable) strings. The StringBuffer class in Java is the same as the string class except it is mutable that is it can be changed.

Java StringBuffer Class Example

In the example below, we are using the object of the StringBuffer class because it provides a function that can reverse the string.

import java.util.Scanner;

public class String_Palindrome {
  // Creating object of Scanner Class
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Taking Input from user
    System.out.println("Please Enter the String: ");
    String input_string = scanner.nextLine();

    // Creating a new StringBuffer object to 
    // reverse the input string
    StringBuffer buffObj = new StringBuffer(input_string);

    // reversing the string with the reverse function 
    buffObj.reverse();
    String reversed_string = buffObj.toString();

    // Checking if Both Strings are palindrome or not
    if (reversed_string.compareTo(input_string) == 0) {
      System.out.println("Your string is Palindrome.");
    } else {
      System.out.println("Your string is not Palindrome.");
    }
  }
}

Output

First Run:
Please Enter the String: 
NAMAN
Your string is Palindrome.

Second Run:
Please Enter the String: 
KAMAN
Your string is not Palindrome.

Java StringBuffer Class Example: Different Method Used

In this example, we are using different methods of StringBuffer class.

public class Main {
  public static void main(String[] args) {
    // Creating a StringBuffer object
    StringBuffer str = new StringBuffer("IncludeHelp");

    // Printing value
    System.out.println("Initial Content: " + str);

    // Appending characters to the end of the StringBuffer
    str.append(" Java Tutorial!");

    // Printing value after appending
    System.out.println("After Appending: " + str);

    // Inserting characters at a specific position
    str.insert(5, " Java");

    // Printing value after insertion
    System.out.println("After Insertion: " + str);

    // Deleting characters from a specific position
    str.delete(5, 10);

    // Printing value after deletion
    System.out.println("After Deletion: " + str);

    // Reversing value of the StringBuffer
    str.reverse();

    // Printing value after reversal
    System.out.println("After Reversal: " + str);
  }
}

Output

Initial Content: IncludeHelp
After Appending: IncludeHelp Java Tutorial!
After Insertion: Inclu JavadeHelp Java Tutorial!
After Deletion: IncludeHelp Java Tutorial!
After Reversal: !lairotuT avaJ pleHedulcnI

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.