Check Palindrome Using Recursion in Java
Problem
A recursive palindrome check compares the outermost pair of characters and, if they match, hands off a narrower window to the next call — shrinking one pair at a time until nothing is left to compare.
Given a string and a pair of index bounds, determine recursively whether it reads the same forwards and backwards.
Java Program
public class PalindromeCheckRecursion {
static boolean isPalindrome(String str, int left, int right) {
if (left >= right) return true; // window has shrunk to nothing left to compare
if (str.charAt(left) != str.charAt(right)) return false; // one mismatch rules it out
return isPalindrome(str, left + 1, right - 1);
}
public static void main(String[] args) {
String str = "racecar";
boolean result = isPalindrome(str, 0, str.length() - 1);
System.out.println(str + " is palindrome: " + result);
}
}Output
Core Logic
Comparing the two ends of the current window and recursing on the window with both ends moved inward reduces the whole check to a chain of single-pair comparisons.
- 1
isPalindrome(str, left, right)tracks the current comparison window with two index bounds. - 2If
str.charAt(left) != str.charAt(right), the call returnsfalseimmediately — one mismatch is enough to rule out a palindrome. - 3Otherwise it recurses with
isPalindrome(str, left + 1, right - 1), narrowing the window by one character from each side. - 4The base case
if (left >= right) return true;fires once the window has shrunk to nothing or a single middle character, meaning every pair matched.
"racecar", the calls compare (r,r), then (a,a), then (c,c), then reach left == right at the middle 'e' and return true all the way back up.Key Point: Each call only ever needs to know the current window's bounds — it doesn't need to remember which pairs already matched, since a mismatch anywhere would already have returned false before this call was ever reached.
Why: The window shrinks by one pair per call, so roughly n/2 calls run, each adding a frame to the call stack before any of them return.