Java Program to Check Palindrome Using Recursion
boolean isPalindrome(String s, int start, int end).Examples
How to Think About It
Algorithm
Code
public class PalindromeChecker { public static boolean isPalindrome(String s, int start, int end) { if (start >= end) { return true; } if (s.charAt(start) != s.charAt(end)) { return false; } return isPalindrome(s, start + 1, end - 1); } public static void main(String[] args) { String input = "madam"; if (isPalindrome(input, 0, input.length() - 1)) { System.out.println(input + " is a palindrome"); } else { System.out.println(input + " is not a palindrome"); } } }
Dry Run
Let's trace the input "madam" through the code
Initial call
Check characters at positions 0 ('m') and 4 ('m'), they match.
Recursive call 1
Check characters at positions 1 ('a') and 3 ('a'), they match.
Recursive call 2
Check characters at positions 2 ('d') and 2 ('d'), start >= end, return true.
Return true up the call stack
Each recursive call returns true, final result is true.
| Call | Start Index | End Index | Characters Compared | Result |
|---|---|---|---|---|
| 1 | 0 | 4 | 'm' vs 'm' | Match, recurse |
| 2 | 1 | 3 | 'a' vs 'a' | Match, recurse |
| 3 | 2 | 2 | 'd' vs 'd' | Start >= End, return true |
Why This Works
Step 1: Base Case
When start >= end, it means all characters matched so far, so return true.
Step 2: Mismatch Check
If characters at start and end differ, return false immediately.
Step 3: Recursive Step
If characters match, call the function again with start+1 and end-1 to check inner substring.
Alternative Approaches
public class PalindromeChecker { public static boolean isPalindrome(String s) { int start = 0, end = s.length() - 1; while (start < end) { if (s.charAt(start) != s.charAt(end)) { return false; } start++; end--; } return true; } public static void main(String[] args) { String input = "madam"; System.out.println(input + (isPalindrome(input) ? " is a palindrome" : " is not a palindrome")); } }
public class PalindromeChecker { public static boolean isPalindrome(String s) { String reversed = new StringBuilder(s).reverse().toString(); return s.equals(reversed); } public static void main(String[] args) { String input = "madam"; System.out.println(input + (isPalindrome(input) ? " is a palindrome" : " is not a palindrome")); } }
Complexity: O(n) time, O(n) space
Time Complexity
The function compares pairs of characters moving inward, so it runs in linear time proportional to the string length.
Space Complexity
Each recursive call adds a new frame to the call stack, so space is linear in the worst case.
Which Approach is Fastest?
The iterative approach uses constant space and is faster in practice, but recursion is good for learning and clarity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive | O(n) | O(n) | Learning recursion, clarity |
| Iterative | O(n) | O(1) | Performance and memory efficiency |
| String reversal | O(n) | O(n) | Simplicity, no recursion |