Java Online Compiler
Example: PalindromeChecker in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// PalindromeChecker import java.util.Scanner; // Main class containing the entry point of the program public class Main { /** * Checks if a given string is a palindrome using recursion. * Ignores non-alphanumeric characters and case. * @param s The input string. * @return true if the string is a palindrome, false otherwise. */ public static boolean isPalindromeRecursive(String s) { // Step 1: Handle null or empty string as a palindrome if (s == null || s.length() == 0 || s.length() == 1) { return true; } // Step 2: Normalize the string: remove non-alphanumeric and convert to lowercase String normalizedString = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); // Step 3: Call the helper function for recursive check return checkPalindrome(normalizedString, 0, normalizedString.length() - 1); } /** * Helper recursive function to check for palindrome. * @param s The normalized string. * @param left The left pointer index. * @param right The right pointer index. * @return true if the substring from left to right is a palindrome, false otherwise. */ private static boolean checkPalindrome(String s, int left, int right) { // Base Case 1: If left pointer crosses or meets the right pointer, it's a palindrome if (left >= right) { return true; } // Step 4: Compare characters at current left and right pointers if (s.charAt(left) != s.charAt(right)) { return false; // Characters don't match, not a palindrome } // Step 5: If characters match, recursively check the inner substring return checkPalindrome(s, left + 1, right - 1); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Step 1: Prompt user for input string System.out.print("Enter a string to check if it's a palindrome: "); String input = scanner.nextLine(); // Step 2: Call the palindrome checker function boolean result = isPalindromeRecursive(input); // Step 3: Print the result if (result) { System.out.println("'" + input + "' is a palindrome."); } else { System.out.println("'" + input + "' is NOT a palindrome."); } // Test with more examples System.out.println("\n--- Testing with pre-defined examples ---"); System.out.println("'Madam' is a palindrome: " + isPalindromeRecursive("Madam")); // True System.out.println("'Racecar' is a palindrome: " + isPalindromeRecursive("Racecar")); // True System.out.println("'A man, a plan, a canal: Panama' is a palindrome: " + isPalindromeRecursive("A man, a plan, a canal: Panama")); // True System.out.println("'hello' is a palindrome: " + isPalindromeRecursive("hello")); // False System.out.println("'' (empty string) is a palindrome: " + isPalindromeRecursive("")); // True System.out.println("'a' (single char) is a palindrome: " + isPalindromeRecursive("a")); // True System.out.println("'ab' is a palindrome: " + isPalindromeRecursive("ab")); // False scanner.close(); } }
Output
Clear
ADVERTISEMENTS