java program to check string is palindrome or not 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 whether string is palindrome using library methods
public class StringPalindromeJava
{
public static void isPalindrome(String str)
{
String strReverse = new StringBuffer(str).reverse().toString();
if(str.equals(strReverse))
{
System.out.println(str + " is palindrome string.");
}
else
{
System.out.println(str + " is not palindrome string.");
}
}
public static void main(String[] args)
{
isPalindrome("eye");
isPalindrome("rotator");
}
}
Example 3: java program to find plaindrome
public class Palindrome {
public static void main(String[] args) {
int num = 121, reversedInteger = 0, remainder, originalInteger;
originalInteger = num;
while( num != 0 )
{
remainder = num % 10;
reversedInteger = reversedInteger * 10 + remainder;
num /= 10;
}
if (originalInteger == reversedInteger)
System.out.println(originalInteger + " is a palindrome.");
else
System.out.println(originalInteger + " is not a palindrome.");
}
}