A palindrome is a string that is spelled the same way forwar
Solution
PalindromeCheck.java
import java.util.Scanner;
public class PalindromeCheck {
public static void main(String[] args) {
// Declaring variables
String str = \"\";
boolean bool1,bool2;
// Scanner Class Object is used to get the inputs entered by the user
Scanner sc = new Scanner(System.in);
// Getting the string entered by the user
System.out.print(\"Enter a Sentence :\");
str = sc.nextLine();
System.out.println(\"\ :: Calling the Non recursive Method ::\");
//Calling the method by passing the string as input.
bool1 = testPalindrome1(str);
//based on the bool1 value the corresponding message will be displayed
if (bool1 == true) {
System.out.println(\":: This is a Palindrome ::\");
} else {
System.out.println(\":: This is not a Palindrome ::\");
}
System.out.println(\"\ :: Calling the recursive Method ::\");
//Calling the method by passing the string as input.
bool2 = testPalindrome2(str);
//based on the bool1 value the corresponding message will be displayed
if (bool2 == true) {
System.out.println(\":: This is a Palindrome ::\");
} else {
System.out.println(\":: This is not a Palindrome ::\");
}
}
/* This is a recursive function which calculates
* whether the String is Palindrome or not using recursive method
* Param:string
* return: boolean
*/
private static boolean testPalindrome2(String str) {
if(str.length() == 0 || str.length() == 1)
return true;
if(str.charAt(0) == str.charAt(str.length()-1))
return testPalindrome2(str.substring(1, str.length()-1));
return false;
}
/* This method will check whether the string is palindrome or not
* If the String is Palindrome then it returns true
* If not,It returns false
* Param:string
* return: boolean
*/
private static boolean testPalindrome1(String str) {
//Declaring local variables
String revstr = \"\";
int count = 0;
//This for loop will reverse the string
for (int i = 0; i < str.length(); i++) {
revstr += str.charAt((str.length() - 1) - i);
}
/* This for loop will compare each character
* in the user entered string and the reversed string
*/
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != revstr.charAt(i))
count++;
}
/* If the two strings are equal then return true
* else return false
*/
if (count == 0)
return true;
else
return false;
}
}
__________________________________________
Output1:
Enter a Sentence :able was ere saw elba
:: Calling the Non recursive Method ::
:: This is a Palindrome ::
:: Calling the recursive Method ::
:: This is a Palindrome ::
_____________________________________________
output2:
Enter a Sentence :radar
:: Calling the Non recursive Method ::
:: This is a Palindrome ::
:: Calling the recursive Method ::
:: This is a Palindrome ::
____________________________Thank You


