Check Whether A String Is A Palindrome Or Not In Java Program
In this article, you will learn how to determine if a given string is a palindrome using various methods in Java. We will explore different programming approaches, providing practical examples and clear explanations for each.
Problem Statement
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. Common examples include "madam," "racecar," or "level." The problem is to develop a Java program that can take an input string and correctly identify whether it fits this definition. Often, a robust palindrome check ignores case differences and non-alphanumeric characters (like spaces, punctuation).
Example
Consider the following examples to illustrate the concept:
- Input: "madam"
- Processed (lowercase, no spaces/punctuation): "madam"
- Is Palindrome? Yes
- Input: "A man, a plan, a canal: Panama"
- Processed: "amanaplanacanalpanama"
- Is Palindrome? Yes
- Input: "hello"
- Processed: "hello"
- Is Palindrome? No
- Input: "Java"
- Processed: "java"
- Is Palindrome? No
Background & Knowledge Prerequisites
To understand the solutions presented, familiarity with the following Java concepts is beneficial:
- String Manipulation: Creating, comparing, and accessing characters within strings.
- Loops:
forandwhileloops for iteration. - Conditional Statements:
if-elseconstructs for decision-making. - Methods: Defining and calling methods.
-
StringBuilderClass: For efficient string modification (optional for some approaches but useful). - Recursion: Understanding how functions can call themselves (for one specific approach).
Use Cases or Case Studies
Checking for palindromes can be useful in various real-world scenarios:
- Text Analysis and Natural Language Processing: Identifying specific patterns in text, analyzing wordplay, or for linguistic research.
- Data Validation: Ensuring user inputs (e.g., specific codes or identifiers) adhere to a palindromic format.
- Educational Tools: As a programming exercise for beginners to practice string manipulation, loops, and conditional logic.
- Game Development: Creating puzzles or challenges based on palindromic sequences.
- Bioinformatics: Analyzing genetic sequences for palindromic repeats, which can have biological significance.
Solution Approaches
We will explore three distinct approaches to check if a string is a palindrome in Java. For all approaches, we will first preprocess the input string to convert it to lowercase and remove all non-alphanumeric characters, ensuring a robust check that ignores case and punctuation.
Approach 1: Two-Pointer Iteration
This approach uses two pointers, one starting from the beginning of the string and the other from the end. They move towards each other, comparing characters at each step.
- One-line summary: Compare characters from both ends of the processed string, moving inwards until pointers meet or a mismatch is found.
// PalindromeCheckTwoPointer
import java.util.Scanner;
public class Main {
// Helper method to preprocess the string
private static String preprocessString(String s) {
StringBuilder cleanedString = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isLetterOrDigit(c)) {
cleanedString.append(Character.toLowerCase(c));
}
}
return cleanedString.toString();
}
// Method to check for palindrome using two pointers
public static boolean isPalindromeTwoPointer(String s) {
String cleaned = preprocessString(s);
int left = 0;
int right = cleaned.length() - 1;
while (left < right) {
if (cleaned.charAt(left) != cleaned.charAt(right)) {
return false; // Mismatch found
}
left++;
right--;
}
return true; // No mismatch found
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Get input string from the user
System.out.print("Enter a string to check for palindrome: ");
String inputString = scanner.nextLine();
// Step 2: Check if it's a palindrome using the two-pointer method
if (isPalindromeTwoPointer(inputString)) {
System.out.println("'" + inputString + "' is a palindrome (Two-Pointer Method).");
} else {
System.out.println("'" + inputString + "' is NOT a palindrome (Two-Pointer Method).");
}
scanner.close();
}
}
Sample Output:
Enter a string to check for palindrome: racecar
'racecar' is a palindrome (Two-Pointer Method).
Stepwise Explanation:
preprocessString(String s):
- Takes the original string
sas input. - Iterates through each character.
- If a character is a letter or a digit, it converts it to lowercase and appends it to a
StringBuilder. - Returns the resulting cleaned string.
isPalindromeTwoPointer(String s):
- First, calls
preprocessString(s)to get a cleaned version of the input. - Initializes
leftpointer to 0 (start of the string) andrightpointer tocleaned.length() - 1(end of the string). - Enters a
whileloop that continues as long asleftis less thanright. - Inside the loop, it compares the characters at
cleaned.charAt(left)andcleaned.charAt(right). - If they are not equal, the string is not a palindrome, and the method immediately returns
false. - If they are equal, both pointers move inwards (
left++,right--). - If the loop completes without finding any mismatches, it means the string is a palindrome, and the method returns
true.
Approach 2: Using StringBuilder.reverse()
Java's StringBuilder class provides a convenient reverse() method, which can be leveraged to quickly check for palindromes.
- One-line summary: Preprocess the string, reverse it using
StringBuilder, and then compare it with the original processed string.
// PalindromeCheckStringBuilder
import java.util.Scanner;
public class Main {
// Helper method to preprocess the string
private static String preprocessString(String s) {
StringBuilder cleanedString = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isLetterOrDigit(c)) {
cleanedString.append(Character.toLowerCase(c));
}
}
return cleanedString.toString();
}
// Method to check for palindrome using StringBuilder.reverse()
public static boolean isPalindromeStringBuilder(String s) {
String cleaned = preprocessString(s);
String reversedCleaned = new StringBuilder(cleaned).reverse().toString();
return cleaned.equals(reversedCleaned);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Get input string from the user
System.out.print("Enter a string to check for palindrome: ");
String inputString = scanner.nextLine();
// Step 2: Check if it's a palindrome using the StringBuilder method
if (isPalindromeStringBuilder(inputString)) {
System.out.println("'" + inputString + "' is a palindrome (StringBuilder Method).");
} else {
System.out.println("'" + inputString + "' is NOT a palindrome (StringBuilder Method).");
}
scanner.close();
}
}
Sample Output:
Enter a string to check for palindrome: A man, a plan, a canal: Panama
'A man, a plan, a canal: Panama' is a palindrome (StringBuilder Method).
Stepwise Explanation:
preprocessString(String s): (Same as Approach 1)
- Cleans the input string by converting to lowercase and removing non-alphanumeric characters.
isPalindromeStringBuilder(String s):
- Obtains the
cleanedversion of the input string. - Creates a new
StringBuilderinstance with thecleanedstring. - Calls the
reverse()method on theStringBuilderto reverse its contents. - Converts the reversed
StringBuilderback to aStringusingtoString(). - Compares the
cleanedstring with thereversedCleanedstring using theequals()method. If they are identical, it's a palindrome andtrueis returned; otherwise,false.
Approach 3: Recursive Approach
This approach defines a function that calls itself to solve smaller subproblems until a base case is reached.
- One-line summary: Recursively compare the first and last characters of the processed string; if they match, check the inner substring.
// PalindromeCheckRecursive
import java.util.Scanner;
public class Main {
// Helper method to preprocess the string
private static String preprocessString(String s) {
StringBuilder cleanedString = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isLetterOrDigit(c)) {
cleanedString.append(Character.toLowerCase(c));
}
}
return cleanedString.toString();
}
// Method to check for palindrome using recursion
public static boolean isPalindromeRecursive(String s) {
String cleaned = preprocessString(s);
return checkRecursive(cleaned, 0, cleaned.length() - 1);
}
private static boolean checkRecursive(String s, int left, int right) {
// Base Case 1: If left pointer crosses or meets right pointer, it's a palindrome
if (left >= right) {
return true;
}
// Base Case 2: If characters at current pointers don't match
if (s.charAt(left) != s.charAt(right)) {
return false;
}
// Recursive Step: Check the inner substring
return checkRecursive(s, left + 1, right - 1);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Get input string from the user
System.out.print("Enter a string to check for palindrome: ");
String inputString = scanner.nextLine();
// Step 2: Check if it's a palindrome using the recursive method
if (isPalindromeRecursive(inputString)) {
System.out.println("'" + inputString + "' is a palindrome (Recursive Method).");
} else {
System.out.println("'" + inputString + "' is NOT a palindrome (Recursive Method).");
}
scanner.close();
}
}
Sample Output:
Enter a string to check for palindrome: Madam, I'm Adam
'Madam, I'm Adam' is a palindrome (Recursive Method).
Stepwise Explanation:
preprocessString(String s): (Same as Approach 1 and 2)
- Cleans the input string by converting to lowercase and removing non-alphanumeric characters.
isPalindromeRecursive(String s):
- Obtains the
cleanedversion of the input string. - Initiates the recursive helper function
checkRecursivewith the cleaned string and pointers to its start and end.
checkRecursive(String s, int left, int right):
- Base Case 1: If
leftis greater than or equal toright, it means all characters have been successfully compared or the string is empty/has one character. In this case, it's a palindrome, sotrueis returned. - Base Case 2: If the character at
leftdoes not match the character atright, the string is not a palindrome, andfalseis returned. - Recursive Step: If the characters match, the function calls itself with
left + 1andright - 1, effectively narrowing the string to check the inner substring. The result of this recursive call determines the overall outcome.
Conclusion
Determining if a string is a palindrome is a fundamental problem in programming, serving as an excellent exercise for string manipulation and algorithmic thinking. We explored three common methods in Java: the two-pointer iterative approach, the concise StringBuilder.reverse() method, and a recursive solution. Each approach has its merits in terms of readability, performance, and demonstration of different programming paradigms.
Summary
- A palindrome reads the same forwards and backward.
- Preprocessing (lowercase, remove non-alphanumeric) is crucial for robust palindrome checks.
- Two-Pointer Iteration: Efficiently compares characters from both ends towards the center.
-
StringBuilder.reverse(): Offers a concise and idiomatic Java way to reverse and compare strings. - Recursive Approach: Breaks the problem down by comparing outer characters and solving for the inner substring.
- The choice of method depends on factors like performance requirements, code readability preferences, and whether recursion is deemed appropriate for the context.