Write a program in Java to input any word and
display if it is a palindrome. (If the word reads
same from left and right then it is a palindrome.
e.g. MADAM)
Answers
Explanation:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner inp= new Scanner(System.in);
System.out.print("Enter the number: ");
int num= inp.nextInt();
int reverse=0, element, remainder;
element = num;
for( ;num!=0;num/=10){
remainder= num % 10;
reverse = (reverse * 10) + remainder;
}
if (element == reverse){
System.out.println("Yes, it is palindrome");
}
else{
System.out.println("No, it is not palindrome");
}
}
}
How do you check if a word is a palindrome in Java?
Create a StringBuffer object by passing the required string as a parameter to the constructor. Reverse the contents of the object using the reverse() method. Convert the StringBuffer object to Sting using the toString() method. Now, compare the String and the reversed one, if true, the given string is a palindrome.