Sunday, 15 February 2015

Java Program to Find Palindromes

A palindrome is a number which has the same value whether you read its digits forwards or backwards e.g. 8, 66, 525 etc. The program below shows how you can use Java to find them. It converts the number to a string, reverses the string then tests whether the reversed string is the same as the original:

andrew@UBUNTU:~/Java$ cat palindrome.java
class palindrome     
  {
  public static void main(String args[])
    {
    for (int a=1;a<1000;a++)
      {
      String s1 = String.valueOf(a);
      String s2 = new StringBuffer(s1).reverse().toString();
      if (s1.equals(s2))
        {
        System.out.println(a + " is a palindrome");
        }
      }
    }
  }
andrew@UBUNTU:~/Java$ javac palindrome.java

andrew@UBUNTU:~/Java$ java palindrome
1 is a palindrome
2 is a palindrome
3 is a palindrome
4 is a palindrome
5 is a palindrome
6 is a palindrome
7 is a palindrome
8 is a palindrome
9 is a palindrome
11 is a palindrome
22 is a palindrome
33 is a palindrome
44 is a palindrome
55 is a palindrome
66 is a palindrome
77 is a palindrome
88 is a palindrome
99 is a palindrome
101 is a palindrome
111 is a palindrome
121 is a palindrome
131 is a palindrome
141 is a palindrome
151 is a palindrome
161 is a palindrome
171 is a palindrome
181 is a palindrome
191 is a palindrome
202 is a palindrome
212 is a palindrome
222 is a palindrome
232 is a palindrome
242 is a palindrome
252 is a palindrome
262 is a palindrome
272 is a palindrome
282 is a palindrome
292 is a palindrome
303 is a palindrome
313 is a palindrome
323 is a palindrome
333 is a palindrome
343 is a palindrome
353 is a palindrome
363 is a palindrome
373 is a palindrome
383 is a palindrome
393 is a palindrome
404 is a palindrome
414 is a palindrome
424 is a palindrome
434 is a palindrome
444 is a palindrome
454 is a palindrome
464 is a palindrome
474 is a palindrome
484 is a palindrome
494 is a palindrome
505 is a palindrome
515 is a palindrome
525 is a palindrome
535 is a palindrome
545 is a palindrome
555 is a palindrome
565 is a palindrome
575 is a palindrome
585 is a palindrome
595 is a palindrome
606 is a palindrome
616 is a palindrome
626 is a palindrome
636 is a palindrome
646 is a palindrome
656 is a palindrome
666 is a palindrome
676 is a palindrome
686 is a palindrome
696 is a palindrome
707 is a palindrome
717 is a palindrome
727 is a palindrome
737 is a palindrome
747 is a palindrome
757 is a palindrome
767 is a palindrome
777 is a palindrome
787 is a palindrome
797 is a palindrome
808 is a palindrome
818 is a palindrome
828 is a palindrome
838 is a palindrome
848 is a palindrome
858 is a palindrome
868 is a palindrome
878 is a palindrome
888 is a palindrome
898 is a palindrome
909 is a palindrome
919 is a palindrome
929 is a palindrome
939 is a palindrome
949 is a palindrome
959 is a palindrome
969 is a palindrome
979 is a palindrome
989 is a palindrome
999 is a palindrome
andrew@UBUNTU:~/Java$