Sunday, January 10, 2016

Java Program To Find Whether the String is Palindrome or not

In The Earlier Post we discussed Java Program To Print Prime Numbers Between 1 to 100 . we will discuss in today post to find whether the given String is Palindrome or not.Frequently ask this program logic in the Technical Round interview, Interviewer wants to know about your programming skill and the way you implementing the code.

Palindrome:
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;

Also check The Post: Java program to find Prime Numbers between 1 to 100



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

Also Read: String in java

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...