Palindrome Number in Java Application

The following Java program application is a Palindrome Number. An integer is a Palindrome if it reads forward and backward in the same way, ignoring any leading minus sign. In this program, we use an input dialog box to get the input and an output dialog box to show the output. I will be using the JCreator IDE in developing the program. To start in this tutorial, first open the JCreator IDE, click new and paste the following code
  1. import javax.swing.JOptionPane;
  2.  
  3. public class Palindrome
  4. {
  5. public static void main(String[] args)
  6. {
  7. long num;
  8. long temp;
  9.  
  10. String inputStr;
  11. String outputStr;
  12.  
  13. inputStr =
  14. JOptionPane.showInputDialog("Enter an integer, "
  15. + "positive or negative");
  16.  
  17. num = Long.parseLong(inputStr);
  18. temp = num;
  19.  
  20. if (num <= 0)
  21. {
  22. num = -num;
  23. inputStr = inputStr.valueOf(num);
  24.  
  25. }
  26. if (isPalindrome (inputStr))
  27. outputStr = temp + " is a palindrome";
  28. else
  29. outputStr = temp + "is not a palindrome";
  30.  
  31. JOptionPane.showMessageDialog(null, outputStr,
  32. "Palindrome Program", JOptionPane.INFORMATION_MESSAGE);
  33. System.exit(0);
  34. }
  35. public static boolean isPalindrome(String str)
  36. {
  37. int len = str.length();
  38. int i, j;
  39.  
  40. j = len - 1;
  41.  
  42. for (i = 0; i <= (len - 1)/2; i++)
  43. {
  44. if (str.charAt(i) != str.charAt(j))
  45. return false;
  46. j--;
  47. }
  48. return true;
  49.  
  50. }
  51. }
Sample run#1: sample run#2 The program algorithm are the following: The first thing that the program does is read the integer. Because the input of the program is string, the string containing the integer is converted into the integer. If the integer is negative, the program changes it to positive. The next step is to convert the integer back to a string and then determine whether the string is palindrome.

Add new comment