Palindrome Program in Java
What is a Palindrome?
A palindrome is a word, phrase, number or sequence of words that reads the same backward as forward .
Here are a few examples:
- abba
- refer
- kayak
- racecar
import java.util.Scanner;
class test
{
public static boolean checkPalindrome(String inStr)
{
if(inStr.length() == 0 inStr.length() == 1)
return true;
if(inStr.charAt(0) == inStr.charAt(inStr.length()-1)) // check first and last char
return checkPalindrome(inStr.substring(1, inStr.length()-1)); //Function calling itself, called recursion
return false;
}
public static void main(String[]args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your string:");
String string = scanner.nextLine();
if(checkPalindrome(string))
System.out.println(string + " is a palindrome");
else
System.out.println(string + " is not a palindrome");
}
}
Related Topics