Java Program of Palindrome

Question:

Astrologist believes that having a palindromic name is very auspicious. As we all know, a palindrome is a word that can be read the same way in either direction. There should not be a space or any special character in the word entered. If yes, display “Invalid Input”. Write a Java program to determine whether a given word is a palindrome or not.

Sample Input 1:

Enter the word : 

Malayalam

Sample Output 1: 

Malayalam is a Palindrome

Sample Input 2:

Enter the word : 

Apple

Sample Output 2: 

Apple is not a Palindrome

Sample Input 3:

Enter the word :

no on

Sample Output 3: 

Invalid Input

Sample Input 4:

Enter the word :

@nnn

Sample Output 4: 

Invalid Input

Code:

Palindrome.java

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Palindrome 
{
    public static void main (String[] args) {
        Scanner sc= new Scanner(System.in);
        
        System.out.println("Enter the word :");
        String str=sc.nextLine();
        int len=str.length();
        
        Pattern p=Pattern.compile("[^a-z0-9]", Pattern.CASE_INSENSITIVE);
        Matcher m=p.matcher(str);
        boolean b=m.find();
       
        if(b)
        {
            System.out.println("Invalid Input");
        }
        else
        {
            String rvs=new String();
            
            for(int i=(len-1); i>=0; i--)
            {
                rvs=rvs+str.charAt(i);
            }
            
            if(str.equalsIgnoreCase(rvs))
            {
                System.out.println(str+" is a Palindrome");
            }
            else
            {
                System.out.println(str+" is not a Palindrome");
            }
        }
    }
}

Recommended:

  1. Array square
  2. Generate number using odd digits
  3. Alternate Number Difference
  4. Next Greatest number
  5. Mark Comparison
  6. Print the characters in descending order
  7. Vowels in a fishBowl
  8. Least offer
  9. Ascending and descending order
  10. Mail Domain
  11. Count repeating words
  12. Sentence – Convert to upper and lower
  13. Count consecutive repeating characters
  14. Zig zag Array
  15. Pass and Fail Count
  16. Search a Course
  17. Average and Grade Calculation
  18. String – Find and replace the character (first occurrence)
  19. Sort the first and second half of an array
  20. Retail Shop
  21. Palindrome
  22. Numerology
  23. InitCap
  24. Array Compatiblilty
  25. Sum of the maximum and the minimum element
  26. String Concatenation
  27. Find Average Age
  28. Login
  29.  

1 thought on “Java Program of Palindrome”

Leave a Comment

Your email address will not be published. Required fields are marked *

x