You are here

Palindrome in Java

Palindrome

Java program to check if a string is a palindrome or not, it's a palindrome if it remains the same on reversal.

For example, "dad" is a palindrome, as its reverse is "dad," whereas "program" isn't, as its reverse is "margorp" that is different from "program."

Some palindrome strings examples are: "j", "mom", "madam", "ab1ba", “12321.”

In the program, a user inputs a string, and we create a new one by reversing it and then compares it with the input string.

Palindrome program in Java

import java.util.*;
 
class Palindrome
{
  public static void main(String args[])
  {
    String original, reverse = ""; // Objects of String class
    Scanner in = new Scanner(System.in);

    System.out.println("Enter a string to check if it's a palindrome");
    original = in.nextLine();

    int length = original.length();

    for (int i = length - 1; i >= 0; i--)
      reverse = reverse + original.charAt(i);

    if (original.equals(reverse))
      System.out.println("The string is a palindrome.");
    else
      System.out.println("The string isn't a palindrome.");
  }
}

Palindrome Java program output:
Palindrome Java program output

Download Palindrome program class file.

Java palindrome program without reversing a string

We compare characters at the beginning and the end of a string and move towards its middle.

import java.util.*;
 
class Palindrome
{
  public static void main(String args[])
  {
    String inputString;
    Scanner in = new Scanner(System.in);
 
    System.out.println("Input a string");
    inputString = in.nextLine();
 
    int length  = inputString.length();
    int i, begin, end, middle;
 
    begin  = 0;
    end    = length - 1;
    middle = (begin + end)/2;
 
    for (i = begin; i <= middle; i++) {
      if (inputString.charAt(begin) == inputString.charAt(end)) {
        begin++;
        end--;
      }
      else
        break;
    }
    if (i == middle + 1)
      System.out.println("Palindrome");
    else
      System.out.println("Not a palindrome");
  }
}

Both the programs consider strings are case sensitive. You can modify them so that they are case insensitive. You can either convert both strings to lower or upper case for this. Try not to alter them as we may require them further in the program.