Java Program to find String is Palindrome or not

In this post you will learn to find String is Palindrome or not. Frequently asking in technical interview about programming logic.
Definition 1 : If Reverse of String is same as Original One then it is called as String Palindrome.
Definition 2: If String Reads the same backward and forward then it is called String palindrome.

Example: Original String="MADAM"

                   Palindrome String="MADAM" //string is palindrome

                   Original String="lucky"

                   Palindrome String="ykcul"// This is NOT String palindrome


Program 1: This Program is developed using String API.

import java.io.*;

class Palindrome
{
public static void main(String args[]) throws IOException
{
String str;
System.out.println("Enter a string");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();
StringBuffer sb=new StringBuffer(str);
String revstr=new String(sb.reverse());
if(revstr.equalsIgnoreCase(str))
System.out.println("String is palindrome");
else
System.out.println("Not a Palindrome String!");
}
}

Output:
Enter a String : MADAM
String is Palindrome;


Program 2: Java Program to find Whether the String is Palindrome or not Using Recursion method.

import java.util.*;

class StringPalindrome{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a String:");
String st=sc.next();
StringPalindrome sp=new StringPalindrome();
String reverseString=sp.reverse(st);
if(st.equalsIgnoreCase(reverseString))
{
System.out.printf("The string is palindrome",st);
}
else
{
System.out.printf("the String is not Palindrome",st);
}
}
//method to return the reverse of string
public String reverse(String str)
{
StringBuilder revStr=new StringBuilder();
for(int i=str.length()-1;i>=0;i--)
{
revStr.append(str.charAt(i));
}
return revStr.toString();
}
}

Output:
Enter a String:   lucky
The String is not Palindrome

No comments:

Post a Comment

Basics of CPP Programs

In this post you will learn fundamental C++ programs. These programs for freshers or beginners. 1 .write a cpp program to display hello w...