Java Program to check the string is palindrome or not


May 7, 2022, Learn eTutorial
871

Here we are explaining how to write a java program to check whether a string is a palindrome or not. So first we have to read the string from the user and we will find out the reverse of the string. Then we will check a string and the reversed string are equal or not. If equal then we will display the string as a palindrome.

How to check the strings are equal or not in java?

We can check whether string1 and string2 are equal or not by using the method equalsIgnoreCase.The syntax of equalsIgnoreCase is shown below.

str2.equalsIgnoreCase(str1);
 
Here str2 and str1 are the string. The equalsIgnoreCase() method returns a true value if both str1 and str2 are equal. If str1 and str2 are not equal then it will return false. The equalsIgnoreCase() check the strings are irrespective of their case.

How to implement the java program to check the string is palindrome or not?

First, we have to declare the class CheckPalindrome.Then open the main function. Declare two string variables str1 and str2. Then read the string from the user into the variable str1.Set str2="".Find out the reverse of the string by using for loop, into the variable str2. Check str1 equals to str2 by using the method equalsIgnoreCase().If the strings are equal then we will display the string is a palindrome. Else display the string is not a palindrome.

What is a palindrome

ALGORITHM

STEP 1: Declare the class CheckPalindrome with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Read the string from the user into the variable str1.

STEP 4: Find out the length of the string into the variable len as str1.length().

STEP 5: By using a for loop, assign i=len-1 and check the condition i>=0 if true then do step 6.

STEP 6: set str2=str2+str1.charAt(i).Increment i by one and repeat step 5.

STEP 7: Check if str1 equals str2 by using the function equalsIgnoreCase() method, if equal then display the string is a palindrome. Else display the string is not a palindrome.

 

Java Source Code

                                          import java.util.Scanner;
public class CheckPalindrome
{
    public static void main(String args[])
    {
        String str1,str2;
        str2="";
        Scanner s = new Scanner(System.in);
        System.out.print("Enter the string :");
        str1 = s.nextLine();
        int len = str1.length();
        for(int i = len - 1; i >= 0; i--)
        {
            str2 = str2 + str1.charAt(i);
        }
        if(str1.equalsIgnoreCase(str2))
        {
            System.out.println("The string is palindrome.");
        }
        else
        {
            System.out.println("The string is not palindrome.");
        }
    }
}
                                      

OUTPUT

Enter the string :madam
The string is palindrome.