Write a Java Program to Check String is palindrome or not using String Buffer.In this program, it is very easy to check the given string is Palindrome or not.
In this program ,First convert the String to StringBuffer. I am reversing the string using reverse() method in String Buffer Class and then comparing the reversed string with original string using compareTo() method in string.
Match the original string with reverse string, If both are equal, then given string is Palindrome, Otherwise Not.
Procedure : :
A string str is taken as an input to the program.I have used Scanner class to read the string from keyboard.
Create a String Buffer object s1 for the str because the reverse() method is in String Buffer.
Then, create a String Buffer object s2 for the s1.
Call the reverse method i.e s1.reverse() reverse the string associated with StringBuffer object.
Call the compareTo() method to compare input string and the resultant reverse string for checking the given string is palindrome or not.
Palindrome: :
radar, madam, mom, dad , etc.
Not Palindrome: :
Codezclub, java, road, car, etc.
The following code accepts a string, and checks whether the given string is Palindrome or not using String Buffer.The Program below is successfully compiled and run on the Windows System to produce desired output.
SOURCE CODE : :
import java.util.Scanner;
public class String_buffer
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter string which u want to check : ");
String str=sc.nextLine();
StringBuffer s1=new StringBuffer(str);
StringBuffer s2=new StringBuffer(s1);
s1.reverse();
System.out.println("Given String is : "+s2);
System.out.println("Reverse String is : "+s1);
if(String.valueOf(s1).compareTo(String.valueOf(s2))==0)
System.out.println(s2 + " is Palindrome");
else
System.out.println(s2 + " is Not Palindrome");
}
}
OUTPUT : :
Enter string which u want to check : madam
Given String is : madam
Reverse String is : madam
madam is Palindrome
Steps: :
Procedure : :
Palindrome: :
Not Palindrome: :
The following code accepts a string, and checks whether the given string is Palindrome or not using String Buffer.The Program below is successfully compiled and run on the Windows System to produce desired output.
SOURCE CODE : :
OUTPUT : :
need an explanation for this answer? contact us directly to get an explanation for this answer