String palindrome in java using reverse method code example

Example 1: String palindrome in java without using reverse method

// String palindrome in java without using reverse method
import java.util.Scanner;
public class StringPalindromeDemo 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter string to check palindrome: ");
      String strInput = sc.nextLine();
      // converting string to char array
      char[] chString = strInput.toCharArray();       
      // storing reverse string
      String strReverse = "";         
      // reading char by char
      for(int a = chString.length - 1; a >= 0; a--) 
      {
         strReverse = strReverse + chString[a];
      } 
      // printing given string and reversed string
      System.out.println("Given string: " + strInput);
      System.out.println("Reverse String: " + strReverse); 
      // check if given string is palindrome
      if(strInput.equals(strReverse))
      {
         System.out.println("string is palindrome.");
      }
      else
      {
         System.out.println("string is not palindrome.");
      }
   }
}

Example 2: palindrome function 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