In this Java Program we are going to see whether the entered string is a Palindrome or not.
Basic idea of finding a Palindrome is very simple, all you to do is reverse the string and compare both the original string and the reversed one. If both are equal then it is a palindrome.
Here is the code of the Java Class (palindrome.java):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.io.*; import java.util.Scanner; public class palindrome { public static void main(String args[]){ Scanner sc = new Scanner(System.in); String mystring, revstring; Boolean Palindrome; mystring = sc.nextLine(); //remove the space mystring = mystring.replace(" ", ""); //remove special characters mystring = mystring.replaceAll("[^A-Za-z0-9\\-]",""); //change case to lowercase mystring = mystring.toLowerCase(); //reverse the string revstring = new StringBuilder(mystring).reverse().toString(); //check if both the entered string and the reverse string are same Palindrome = new String(mystring).equals(revstring); //if yes then print "Palindrome" if(Palindrome){ System.out.println("Palindrome"); }else{ System.out.println("Not a Palindrome"); } } } |
This Java Program followed the below steps to find whether the string is Palindrome:
1. Firstly get the entered string using sc.nextLine() (where sc is the Scanner object) and store it in mystring variable.
2. Secondly remove the spaces between the string.
3. Thirdly remove any special characters to avoid confusion finding the palindrome.
4. Now, the important step is to reverse the string and store it in a new variable revstring.
5. Finally check if both the entered string and the reversed string are same, if yes, then print “Palindrome” or else print “Not a Palindrome”
Few palindrome words and sentences to check the Java program:
1. madam
2. civic
3. Madam, I’m Adam
4. A man, a plan, a canal: Panama.
5. No lemon, no melon.
If you wish you can download the script below:
Same palindrome script is written in PHP also, If you are a web developer you may want to have a look:
http://www.tutorialsmade.com/php-program-find-palindrome/