Special words are those words which start and end with the same letter. Examples: EXISTENCE, COMIC, WINDOW Palindrome words are those words which read the same from left to right and vice versa. Examples: MALAYALAM, MADAM, LEVEL, ROTATOR, CIVIC All palindromes are special words, but all special words are not palindromes. Write a program to accept a word and check and print whether the word is a palindrome or only a special word.
Topic: Palindrome and special words
Answer
import java.util.Scanner;
class SpecialWord { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter a word : "); String w = sc.next().toUpperCase();
String rev = ""; for(int i = w.length() - 1; i >= 0; i--) rev = rev + w.charAt(i);
if(w.equals(rev)) System.out.println(w + " is a Palindrome word"); else if(w.charAt(0) == w.charAt(w.length() - 1)) System.out.println(w + " is only a Special word"); else System.out.println(w + " is not a Special word"); } }
The whole question turns on the ORDER of the two tests, and the question itself tells you why: "all palindromes are special words, but all special words are not palindromes".
Since every palindrome is automatically special, the palindrome test must come FIRST. If you tested for special first, MADAM would be reported as merely special and the palindrome case would never be reached. Recognising that one condition is a subset of the other is the real skill here.
Reversing: build rev by walking the string backwards from length() - 1 down to 0. Compare with equals(), never with == — the latter compares memory addresses and would give false even for identical text.
Converting to uppercase first makes the comparison case-insensitive, so Madam is correctly recognised.
Trace the examples: MADAM reverses to MADAM, so palindrome. COMIC reverses to CIMOC, which differs, but C equals C, so it is only a special word. HELLO fails both tests.
w String - the word entered, converted to uppercase rev String - the word built up in reverse i int - loop variable sc Scanner - object used to read input