Palindrome Java Program

Palindrome Definition

“A String is palindrome if it remains unchanged when reversed.”

For Example : String “dad” is a palindrome as reverse of “dad” is “dad” whereas
“program” is not a palindrome. Some other palindrome strings are “nitin”,”mom”, “madam”, “abcba” etc.

Below is simple Java program to check input String is Palindrom or not.

class Palindrome1 {
	public static void main(String args[]) {
		String original, reverse = "";
		Scanner in = new Scanner(System.in);

		System.out.println("Enter a string to check if it is 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("Entered string is a palindrome.");
		else
			System.out.println("Entered string is not a palindrome.");

	}
}

Output

Enter a string to check if it is a palindrome
nitin
Entered string is a palindrome.

Enter a string to check if it is a palindrome
Saurabh
Entered string is not a palindrome.

In above program you find out very simple way to check input string is palindrome but in below program you will see to check palindrome string with minimum number of operations because here dividing text in half size and compare with rest of part of String.

import java.util.*;

class Palindrome2
{
  public static void main(String args[])
  {
    String inputString;
    Scanner in = new Scanner(System.in);

    System.out.println("Enter a string to check if it is a palindrome");
    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("Entered string is a palindrome.");
    }
    else {
      System.out.println("Entered string is not a palindrome.");
    }
  }
}

Output

Enter a string to check if it is a palindrome
nitin
Entered string is a palindrome.

Enter a string to check if it is a palindrome
Saurabh
Entered string is not a palindrome.

More

For more Algorithms and Java Programing Test questions and sample code follow below links

Advertisements

One thought on “Palindrome Java Program”

This site uses Akismet to reduce spam. Learn how your comment data is processed.