how to find a palindrome in java code example

Example 1: Java program to check palindrome string using recursion

import java.util.Scanner;
public class RecursivePalindromeJava 
{
   // to check if string is palindrome using recursion
   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: palindrome in java

package test
//The function below checks if a string is a palindrome
//True = Is a palindrome & False = Not a palindrome
	public boolean isPalindromString(String text){
    	String reverse = reverse(text);
      	if(text.equals(reverse))
    	{
        	return true;
      	}
      
      	return false;
    }
//This function returns the reverse String of its input.
//Ex. if given "hello", it will return "olleh"
	public String reverse(String input)
    {     
		if(input == null || input.isEmpty())
        {
			return input;
        }
return input.charAt(input.length()- 1) + reverse
                         (input.substring(0, input.length() - 1));
    }

Tags:

Java Example