Check whether given String is Palindrome or not in Java [Java interview]

Check whether given String is Palindrome or not in Java

This article will help you to understand Java Program to Check Palindrome.

Palindrome is a String or numeric value which remains same after reversing it. e.g. 12321, 345543, KANAK, MADAM etc. We can check if given string is palindrome or not by reverse it and then compare it with original string.

Java Program to Check Palindrome

public class Palindrome {

	public boolean isPalindrome(String inputStr)
	{
		String reversedStr = "";
		
		if(inputStr == null) 
		{
			System.out.println("PLEASE ENTER A VALID STRING.");
			return false;
		}
		
		else if (inputStr.length()==1)
			return true;
			
		//Here we also get a Reverse String program as a bonus!
		for(int i=inputStr.length()-1;i>=0;i--)
		{
			reversedStr+=inputStr.charAt(i);
		}
		
		// Here we can also use Equal instead of equalsIgnoreCase if we want case sensitive comparison. 
		if(inputStr.equalsIgnoreCase(reversedStr)) return true;
		
		return false;
	}

	public static void main(String s[])
	{
		
		String inputStr = "Madam"; // Also try different inputs as KANAK, 123321 etc.
		//String inputStr = "abcdef"; // try some invalid input
		
		Palindrome palindrome = new Palindrome();
		boolean isPalindrome= palindrome.isPalindrome(inputStr);
		if(isPalindrome) System.out.println(inputStr+" is Palindrome.");
		else System.out.println(inputStr+" IS NOT palindrome.");
	}
}

Output Madam is Palindrome.

Now try some string, say “abcdef” which is not palindrome. It’s already given as commented in program.

Output abcdef IS NOT palindrome.