Java program For Checking A Palindrome

No comments
In this particular tutorial we will write a program to check whether a given string string is a palindrome or not. Before we start writing the actual code we should know ,what is a palindrome string?
A string is called palindrome if it remains same after reversing, for example- suppose we have a string "racecar" now if we reverse the order of its alphabets it will still remain the same string "racecar" , so "racecar" is a palindrome.Similarly there are some other palindrome strings like-"mom","dad","civic" and many more, you can use any of these as a palindrome.

What is not a palindrome? A string like "java" is not palindrome because on reversing the sequence of its alphabet it becomes "avaj" which is different from "java".
Logic we are going to apply for writing our program is this- first we will read the user input from keyboard using java Scanner class and store it in a String variable.Then we will reverse the string and store it in another String variable and at last we will compare both the strings using equals method, and print a message on the screen according to the result, and we are done.
Program-
package in.blogger.tutorialsinn.classes;

import java.util.Scanner;

class Palindrome{
 public static void main(String args[]) {

  // scanning the user input
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter the string you want to check");
  String orig = sc.next();

  // reversing the string
  String rev = "";
  for (int i = orig.length() - 1; i >= 0; i--) {

   rev = rev + orig.charAt(i);
  }

  System.out.println("reverse string is " + rev);

  // checking for equality and printing the result
  if (orig.equals(rev))
   System.out.println("Given string is a palindrom");
  else
   System.out.println("string is not palindrom");

 }

}
Program output-
Enter the string you want to check
civic
reverse string is civic
Given string is a palindrom

This is one of the important questions asked in java interviews as a fresher.
This was the java code for checking a word for palindrome what if someone asks you for checking a number for palindrome?
Don't worry here is the code for checking whether a given number is palindrome or not


No comments :

Post a Comment