C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

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 
		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.








COMMENTS