DEV Community

Sid Lohith
Sid Lohith

Posted on • Originally published at flowerbrackets.com

Java program to check palindrome string using recursion

How to check if a string is a palindrome in java using recursion in java is the most common java interview question.

Recursion means a function calling itself. In this java program first “checkPalindrome()” method with String parameter “str” is created.

This method first checks if user entered string length is 0 or 1 using if statement. Here, if string length is equal to 0 or 1 then string is palindrome.

import java.util.Scanner;
public class RecursivePalindromeJava
{
public static boolean checkPalindrome(String str)
{
if(str.length() == 0 || str.length() == 1)
return true;
if(str.charAt(0) == str.charAt(str.length() - 1))
return checkPalindrome(str.substring(1, str.length() - 1));
return false;
}
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a string : ");
String strInput = sc.nextLine();
if(checkPalindrome(strInput))
{
System.out.println(strInput + " is palindrome");
}
else
{
System.out.println(strInput + " not a palindrome");
}
sc.close();
}
}

Output:

Please enter a string : mom
mom is palindrome.

Top comments (0)