Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Javatutorial Palindrome program in Java

Related Tutorials


 
 

Share on Google+Share on Google+

Palindrome program in Java

Advertisement
Palindrome program in Java helps programmers to determine if a number or string is palindrome or not. palindrome number or string remains unchanged when reversed. For example Eve, Eva, can I stab bats in a cave, Bob, 212, 141, etc. The logic used in Java program behind finding a number or sting is palindrome or not is just to reverse the number or string.

Palindrome program in Java helps programmers to determine if a number or string is palindrome or not. palindrome number or string remains unchanged when reversed. For example Eve, Eva, can I stab bats in a cave, Bob, 212, 141, etc.

The logic used in Java program behind finding a number or sting is palindrome or not is just to reverse the number or string. Then the reverse number or string is checked with the original number or string. When they match the number or string is palindrome, if they don't, the number or string is not palindrome.

First a palindrome class name is defined. After that any number or string is entered by user and reversed by program. Once reversed it will match it with original number or string and display the result to whether the number or string entered is palindrome or not. If the given number is larger, then it will display a message "Out of range!"

*A program can be made to check both the number and string. However, the example below checks only the number.

Example of Palindrome program in Java:

import java.io.*;

public class Palindrome  {
  public static void main(String [] args){
  try{
  BufferedReader object = new BufferedReader(
  new InputStreamReader(System.in));
  System.out.println("Enter number");
  int num= Integer.parseInt(object.readLine());
  int n = num;
  int rev=0;
  System.out.println("Number: ");
  System.out.println(" "+ num);
  for (int i=0; i<=num; i++){
  int r=num%10;
  num=num/10;
  rev=rev*10+r;
  i=0;
  }
  System.out.println("After reversing the number: "+ " ");
  System.out.println(" "+ rev);  
  if(n == rev){
  System.out.print("Number is palindrome!");
  }
  else{
  System.out.println("Number is not palindrome!");
  }
  }
  catch(Exception e){
  System.out.println("Out of range!");
  }
  }
}
Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 3, 2013

Related Tutorials

Discuss: Palindrome program in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com