152k views
1 vote
Write a recursive method that tests whether a string is a palindrome. It should return a boolean T or F depending on whether or not the string is a palindrome,

User Ercument
by
8.4k points

1 Answer

4 votes

Answer:

// program in java.

// library

import java.util.*;

// class definition

class Main

{

// recursive function to check palindrome

public static boolean isPalin(String str){

// base case

if(str.length() == 0 ||str.length()==1){

return true;

}

// if first character is equal to last

if(str.charAt(0) == str.charAt(str.length()-1))

{

// recursive call

return isPalin(str.substring(1, str.length()-1));

}

// return

return false;

}

// main method of the class

public static void main (String[] args) throws java.lang.Exception

{

try{

// object to read input

Scanner scr=new Scanner(System.in);

System.out.print("Enter a string:");

// read string from user

String myString =scr.nextLine();

// call function to check palindrome

if (isPalin(myString)){

System.out.println("Given String is a palindrome");

}

// if string is not palindrome

else{

System.out.println("Given String is not a palindrome");

}

}catch(Exception ex){

return;}

}

}

Step-by-step explanation:

Read a string from user and assign it to variable "myString" with scanner object. Call the method isPalindrome() with string input parameter.In this method, if length of string is 0 or 1 then it will return true(base case) otherwise it will call itself and compare first character with last character.If string is palindrome then function will return true else return false.

Output:

Enter a string:ababa

Given String is a palindrome

User Nanuqcz
by
8.2k points