Java program to check Palindrome

A palindrome is a word, phrase, number, or other sequence of symbols or elements that reads the same forward or reversed. 
For example: 12121 is palindrome as it reads same forward or reversed. madam is also a palindrome .
This is very simple interview question.There are many ways to check if given string is palindrome or not.

Reversing a String and then comparing it with input String:

package org.arpit.java2blog;
import java.util.Scanner;

public class StringFullLoopPalindrome {


 public static void main(String[] args) {

  Scanner scanner = new Scanner(System.in);
  System.out.print("Enter string : ");

  String str = scanner.nextLine();
  String reverseStr = "";

  for(int i = str.length() - 1; i >= 0; i--){
   reverseStr = reverseStr + str.charAt(i);
  }

  if(str.equals(reverseStr)){
   System.out.println("String is palindrome");
  } else {
   System.out.println("String is not palindrome");
  }
 }
}

Run above program, you will get following output:
Enter string : 12121
String is palindrome
Enter a string : Apple
String is not palindrome

Using half loop,Moving from both end of String simultaneously:

package org.arpit.java2blog;
import java.util.Scanner;

public class StringUsingHalfLoop {

 public static void main(String[] args) {
  Scanner scanner = new Scanner(System.in);
  System.out.print("Enter a string : ");

  String str = scanner.nextLine();
  boolean isPalin=isPalindrome(str);
  if(isPalin)
   System.out.println("String is Palindrome");
  else
   System.out.println("String is not Palindrome");
  
 }

 static boolean isPalindrome(String str)
 {
  for (int i = 0,j=str.length()-1; i <str.length()/2; i++,j--) {

   if(str.charAt(i)!=str.charAt(j))
   {
    return false;
   }

  }
  return true;
 }

}
 
Run above program, you will get following output:
Enter a string : madam
String is Palindrome
Enter a string : adam
String is not Palindrome

Using StringBuilder's reverse() function:

package org.arpit.java2blog;

import java.util.Scanner;

public class StringPalindrome {

 public static void main(String[] args) {
   Scanner scanner = new Scanner(System.in);
      System.out.print("Enter string : ");
           
      String str = scanner.nextLine();
      StringBuilder strBuilder = new StringBuilder(str);
           
      strBuilder.reverse();
           
      if(str.equals(strBuilder.toString())){
          System.out.println("String is palindrome");
      } else {
          System.out.println("String is not palindrome");
      }

 }

}
Run above program, you will get following output:
Enter a string : stats
String is palindrome
Enter a string : 1212121
String is palindrome

Please go through java interview programs for more such programs.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012