Write a Java program to check whether a given word is a palindrome or not. for e.g. MADAM is a palindrome but eat is not.
Question
Write a Java program to check whether a given word is a palindrome or not.
For example:
MADAM
is a palindromeeat
is not a palindrome.
Solution
Sure, here is a simple Java program that checks if a given word is a palindrome or not:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a word:");
String word = scanner.nextLine();
String reversedWord = new StringBuilder(word).reverse().toString();
if(word.equalsIgnoreCase(reversedWord)) {
System.out.println(word + " is a palindrome.");
} else {
System.out.println(word + " is not a palindrome.");
}
}
}
Here's how it works:
-
We import the Scanner class which is used to get user input.
-
We create a new instance of the Scanner class.
-
We prompt the user to enter a word.
-
We read the user's input using the
nextLine()
method of the Scanner instance. -
We create a new StringBuilder instance with the user's word, reverse it, and convert it back to a String.
-
We compare the reversed word with the original word using the
equalsIgnoreCase()
method. This method returns true if the two strings are equal, ignoring case considerations. -
If the original word and the reversed word are equal, we print that the word is a palindrome. Otherwise, we print that the word is not a palindrome.
Similar Questions
Write a program in java to accept a number and chech whether it is a palindrome number or not. Do the program without using modulus operator and String.
Write a programme to check whether given input is palindrome or notConstraintsABC != PalindromeMAM == Palindrome123 != Palindrome151 == Palindrome
Write a C++ program to check if a given number is a palindrome. A palindrome is a number that remains the same when its digits are reversed.
Write a java program to accept a String and the perform the following operations:a) Count the number of words with the first and the last letter being same.
Write a python program to count the number of palindrome strings that occurred in the given string.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.