You are here

Palindrome in Java

Palindrome in Java: Java program to check if a string is a palindrome or not. A string is a palindrome if it remains unchanged when reversed, for example, "dad" is a palindrome as reverse of "dad" is "dad" whereas "program" isn't a palindrome as its reverse is “margorp” which is different from "program". Some examples of palindrome strings are "mom", "madam", "abcba", “12321”, "c++&++c". In our program a user will input a string and we create a new string which will be its reverse and then we compare it with the input string.

Palindrome program in Java

  1. import java.util.*;
  2.  
  3. class Palindrome
  4. {
  5.    public static void main(String args[])
  6.    {
  7.       String original, reverse = ""; // Objects of String class
  8.       Scanner in = new Scanner(System.in);
  9.      
  10.       System.out.println("Enter a string to check if it is a palindrome");
  11.       original = in.nextLine();
  12.      
  13.       int length = original.length();
  14.      
  15.       for (int i = length - 1; i >= 0; i--)
  16.          reverse = reverse + original.charAt(i);
  17.          
  18.       if (original.equals(reverse))
  19.          System.out.println("The string is a palindrome.");
  20.       else
  21.          System.out.println("The string isn't a palindrome.");
  22.          
  23.    }
  24. }      

Palindrome Java program output:
Palindrome Java program output

Download Palindrome program class file.

Java palindrome program without reversing a string

Another method to check palindrome: We can compare characters at the beginning and at the end of a string and move towards the middle of the string.

  1. import java.util.*;
  2.  
  3. class Palindrome
  4. {
  5.   public static void main(String args[])
  6.   {
  7.     String inputString;
  8.     Scanner in = new Scanner(System.in);
  9.  
  10.     System.out.println("Input a string");
  11.     inputString = in.nextLine();
  12.  
  13.     int length  = inputString.length();
  14.     int i, begin, end, middle;
  15.  
  16.     begin  = 0;
  17.     end    = length - 1;
  18.     middle = (begin + end)/2;
  19.  
  20.     for (i = begin; i <= middle; i++) {
  21.       if (inputString.charAt(begin) == inputString.charAt(end)) {
  22.         begin++;
  23.         end--;
  24.       }
  25.       else {
  26.         break;
  27.       }
  28.     }
  29.     if (i == middle + 1) {
  30.       System.out.println("Palindrome");
  31.     }
  32.     else {
  33.       System.out.println("Not a palindrome");
  34.     }  
  35.   }
  36. }

Both the above codes consider strings as case sensitive, you can modify them so that they ignore the case of the string. You can either convert both strings to lower or upper case for this. Try not to modify the original strings as they may be further required in the program.