Pages

palindrome



Write a program to print whether the given numberr is palindrome or not?

Source code of the program:


import java.util.*;

class Palindrome
{
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 of the program:
















Another method to check palindrome:
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 above code consider a string as case sensitive, you can modify them so that they are not case sensitive.