Home » Java programming language

Explain StringBuffer with an example in Java

What is StringBuffer and how to use its object to reverse a string? In this article we are going to learn about how to use an object of StringBuffer class and function of String class to check whether a string is palindrome or not?
Submitted by Manu Jemini, on September 28, 2017

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

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

Note: A Palindrome is a string of characters which reads the same backward as forwards.

Java program to check whether string is palindrome or not?

import java.util.Scanner;

public class String_Palindrome 
	public static void main(String[] args) 
	{	// Creating object of Scanner Class
		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 
		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.");
			System.out.println("Your string is not Palindrome.");


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

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

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.