My First Post - Palindrome String in Java
What is a Palindrome ?
A palindrome is a sequence of characters, numbers, or symbols that reads the same forward as it does backward. In general terms, it is a symmetrical arrangement. For example, the number 121 or the date 02/02/2020 are palindromes because their sequence remains identical regardless of the direction from which you read them.
What is a String Palindrome?
In programming, a String palindrome refers specifically to a sequence of characters (a word, phrase, or sentence) that maintains its identity when reversed. When checking for string palindromes, developers often have to decide how to handle non-alphanumeric characters (like spaces and punctuation) and letter casing.
For instance:
- "Level" is a palindrome if you ignore the capital "L."
- "Taco cat" is a palindrome if you ignore the space in the middle.
This Java program demonstrates a straightforward approach to checking if a word is a palindrome while enforcing a specific casing rule. The logic first captures user input and converts it to lowercase to perform a standardized reversal using the StringBuilder class. However, the program adds a unique conditional layer: it only validates the palindrome if the original input was provided entirely in uppercase. If the input meets this criteria, the code compares the original string (in its lowercase form) against its reversed version to determine if it reads the same backward and forward. This makes the script a practical example of combining string manipulation, object-oriented methods like reverse(), and conditional flow control to handle user-specific formatting requirements.
// Written by @Varnit_Baiswar
import java.util.Scanner;
public class String_palindrome {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a Word");
String str = in.next();
String cl_str = str.toLowerCase();
StringBuilder dstr = new StringBuilder(cl_str);
String nstr = dstr.reverse().toString();
if (str.equals(str.toUpperCase())) {
if (nstr.equals(cl_str)) {
System.out.println("It is a Palindrome");
} else {
System.out.println("It is not a Palindrome");
}
} else {
System.out.println("The String is Not in Uppercase");
}
}
}