java program for palindrome number using recursion code example
Example 1: Java program to check palindrome string using recursion
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();
}
}
Example 2: Java program to check palindrome number using recursion
public class PalindromeNumberRecursion
{
static int palindromeRecursion(int number, int temp)
{
if(number == 0)
return temp;
temp = (temp * 10) + (number % 10);
return palindromeRecursion(number / 10, temp);
}
public static void main(String[] args)
{
int number = 141;
int temp = palindromeRecursion(number, 0);
if(temp == number)
{
System.out.println("number is palindrome.");
}
else
{
System.out.println("number is not palindrome.");
}
}
}