You are here

Palindrome in Java

Java program to check if a string is a palindrome or not, a string is 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 are: "mom", "madam", "ab1ba", “12321.” In the program, a user inputs a string, and we create a new string 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 ignore its case. You can either convert both strings to lower or upper case for this. Try not to alter the original strings as we may require them further in the program.

Share this