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

About Saurabh Gupta

My Name is Saurabh Gupta, I have approx. 10 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.
This entry was posted in Algorithm, Data Structure, Java, Programming Test and tagged , , , , . Bookmark the permalink.

One Response to Palindrome Java Program

  1. Pingback: Frequently Asked Algorithms and Programs in Interviews | Facing Issues On IT

Comments are closed.