Palindrome Program in Java
A string is said to be a palindrome if the reverse of the string is same as the original string.
This can be explained with the help of examples given below:
Example: If the given string is 'abcba ' when we reverse the string we get the same string as output,hence it is said to be a palindrome.This can be explained with the help of examples given below:
Input: madam
output: Palindrome
Input: system
Output: Not Palindrome
Program
import java.lang.*;import java.io.*;
import java.util.*;
public class palindrome
{
public static void main(String a[])
{
String str = "madam";
StringBuffer sb = new StringBuffer(str);
sb.reverse();
String str1 = sb.toString();
if(str.equals(str1))
{
System.out.println(" The given string is palindrome :"+str);
}
else
{
System.out.println("The given string is not palindrome :"+str);
}
}
}
Output:
The given string is palindrome :madam
First we consider a String, then we pass the string into the StringBuffer object, here sb is a StringBuffer object. Since String is immutable we pass the object of String to StringBuffer object, once the String is assigned it cannot be changed or modified so to avoid the problem we consider a StringBuffer object.
After this the method of StringBuffer class i.e "reverse()", the purpose of this method is to reverse the given String; after reversing we cannot compare the String and StringBuffer. To make the 2 objects comparable they should be of the sametype. So after performing the reverse operation we change the StringBuffer object back to string by using the method "toString()".
Finally when both the objects are in the String type so we compare them by using the "equals()" method.
If both the String are equal then we get the result as "The Given String is palindrome" otherwise we get the result as "The Given String is not palindrome".

0 Comments