Palindrome number is a number which remains the same when reversed, for example, 121, 313, 525, etc.
Example
Let us now see an example to check palindrome −
public class Palindrome { public static void main(String[] args) { int a = 525, revVal = 0, remainder, val; val = a; System.out.println("Number to be checked = "+a); while( a != 0 ) { remainder = a % 10; revVal = revVal * 10 + remainder; a /= 10; } if (val == revVal) System.out.println("Palindrome!"); else System.out.println("Not a palindrome!"); } }
Output
Number to be checked = 525 Palindrome!
Example
Let us now check for palindrome string such as “aba”, “wow”, etc −
public class Demo { public static void main (String[] args) { String str = "ABA"; String strRev = new StringBuffer(str).reverse().toString(); if (str.equals(strRev)) System.out.println("Palindrome!"); else System.out.println("Not a Palindrome!"); } }
Output
Palindrome!