A word, phrase, number or sequence that reads the same backwards as forwards
String = reverse of a String
e.g MADAM, MOM, 01022010 etc.
Let’s see different ways how we can determine, if a word or string is palindrome or not in Java.
package trypkg; public class Pallindrom { public static void main(String[] args) { String str = "madam", revStr = ""; for(int i=str.length()-1; i>= 0; i--) revStr = revStr + str.charAt(i); if(revStr.equals(str)) System.out.println(str + " is a palindrome"); else System.out.println(str + " is not a palindrome"); /* ****Another way to find palindrome**** *if(str.equalsIgnoreCase(new StringBuilder(str).reverse().toString())) * System.out.println(str + " is a palindrome"); *else * System.out.println(str + " is not a palindrome"); */ } }
For integer entry:
public class Pallindrom { public static void main(String[] args) throws IOException { System.out.println("Enter a no. to verify palindrome"); Scanner sc = new Scanner(System.in); int Num = sc.nextInt(); int temp = Num; int revNum = 0; int Rem = 0; while(Num > 0){ Rem = Num % 10; revNum = (revNum * 10) + Rem; Num = Num / 10; } if(temp == revNum){ System.out.println(temp + " is a palindrome number"); } else{ System.out.println(temp + " is NOT a palindrome number"); } } }
Output:
Enter a no. to verify palindrome
151
151 is a palindrome number