Check Palindrome in Java Using Different Methods
Discover various methods for checking if a string is a palindrome in Java. Use recursion and string manipulation to efficiently determine if a string is a palindrome, ignoring spaces, punctuation, and capitalization.
In this blog, we will write a program to check palindrome in Java. A palindrome is a word, phrase, number, or other sequence of characters that reads same forward and backward (ignoring spaces, punctuation, and capitalization).
For example, the following words are palindromes:
- “racecar”
- “level”
- “madam”
Problem: Write a Java method that takes in a string as a parameter and returns a boolean indicating whether the string is a palindrome or not. The method should ignore spaces, punctuation, and capitalization when determining whether the string is a palindrome. The method should be able to handle strings of any length.
Example:
- Input: “racecar”
- Output: true
- Input: “A man, a plan, a canal, Panama!”
- Output: true
- Input: “Hello, world!”
- Output: false
Method 1: Program to Check Palindrome in Java Using a Loop
- Scanner for Input: The program uses Scanner to take input from the user.
- Convert to Lowercase: To ignore case sensitivity, it converts the string to lowercase.
- Assume Palindrome: It assumes the string is a palindrome initially.
- Set Pointers: start begins at the first character, end at the last.
- Loop: Run a loop until the two pointers meet in the middle.
- Compare characters at start and end.
- If they’re different, set isPalindrome to false and exit the loop.
- Otherwise, move start forward and end backward.
- Output Result: It prints whether the string is a palindrome based on the isPalindrome variable.
import java.util.Scanner; // Import the Scanner class for user input
public class PalindromeChecker {
public static void main(String[] args) { // Create a Scanner object to read user input Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a string System.out.print("Enter a string to check if it is a palindrome: "); String original = scanner.nextLine(); // Read the input string
// Close the scanner as we no longer need it scanner.close();
// Convert the string to lowercase to make the check case-insensitive original = original.toLowerCase();
// Assume the string is a palindrome until proven otherwise boolean isPalindrome = true;
// Initialize two pointers, one at the start and one at the end of the string int start = 0; int end = original.length() - 1;
// Loop to compare characters from both ends while (start < end) { // Check if characters at start and end are different if (original.charAt(start) != original.charAt(end)) { isPalindrome = false; // Mark as not a palindrome break; // Exit the loop if a mismatch is found } // Move pointers towards the center start++; end--; }
// Output the result if (isPalindrome) { System.out.println("The string \"" + original + "\" is a palindrome."); } else { System.out.println("The string \"" + original + "\" is not a palindrome."); } }}
Explore popular Java Courses
Best-suited Java courses for you
Learn Java with these high-rated online courses
Method 2: Program to Check Palindrome in Java Using a Recursion
Recursive Method Definition:
- The method isPalindrome takes the string, a starting index (start), and an ending index (end).
- Base Case: If start has reached or crossed end, it returns true (all characters matched).
- Character Comparison: It compares characters at start and end. If they don’t match, it returns false.
- Recursive Call: If characters match, it calls itself with start + 1 and end - 1, moving inward.
Main Method:
- Scanner for Input: Prompts the user to enter a string and reads it.
- Convert to Lowercase: To ignore case sensitivity, it converts the string to lowercase.
- Recursive Palindrome Check: Calls isPalindrome with start at 0 and end at original.length() - 1.
- Output Result: It prints whether the string is a palindrome based on the result of isPalindrome.
import java.util.Scanner; // Import the Scanner class for user input
public class PalindromeCheckerRecursive {
// Recursive method to check if a substring is a palindrome public static boolean isPalindrome(String str, int start, int end) { // Base case: If pointers have crossed, it's a palindrome if (start >= end) { return true; } // Check if characters at the start and end are different if (str.charAt(start) != str.charAt(end)) { return false; } // Recursive call with moved pointers towards the center return isPalindrome(str, start + 1, end - 1); }
public static void main(String[] args) { // Create a Scanner object to read user input Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a string System.out.print("Enter a string to check if it is a palindrome: "); String original = scanner.nextLine(); // Read the input string
// Close the scanner as we no longer need it scanner.close();
// Convert the string to lowercase to make the check case-insensitive original = original.toLowerCase();
// Check if the string is a palindrome using recursion boolean isPalindrome = isPalindrome(original, 0, original.length() - 1);
// Output the result if (isPalindrome) { System.out.println("The string \"" + original + "\" is a palindrome."); } else { System.out.println("The string \"" + original + "\" is not a palindrome."); } }}
Experienced AI and Machine Learning content creator with a passion for using data to solve real-world challenges. I specialize in Python, SQL, NLP, and Data Visualization. My goal is to make data science engaging an... Read Full Bio