Find a String is Palindrome or Not in Java

You are currently viewing Find a String is Palindrome or Not in Java

Hello Guys! In this tutorial, You will know the topic of Find a String is Palindrome or Not in Java. Firstly, We need to talk about a palindrome string and how to do a task using the java program? Let’s move on to this tutorial.

Palindrome String

It is nothing but if the string read from left to right is equal to the string read from right to left.

For example, If the input is “MADAM” then it will be a palindrome string because the reverse string is also the same.

If the input is “SIR” then it will be not a palindrome string because the reverse string is not the same.

Find a String Is Palindrome Or Not in Java

This is the example program to find a string is palindrome or not in java here.

class Main {
  public static void main(String[] args) {

    String str = "alphaahpla", reverseStr = "";
    
    int strLength = str.length();

    for (int i = (strLength - 1); i >=0; --i) {
      reverseStr = reverseStr + str.charAt(i);
    }

    if (str.toLowerCase().equals(reverseStr.toLowerCase())) {
      System.out.println(str + " is a Palindrome String.");
    }
    else {
      System.out.println(str + " is not a Palindrome String.");
    }
  }
}

Source Code Explanation

Initially, We have to define the respective variable to store the input string. The length of the string will calculate using the strlength() function. After executing the program, The for loop will use to check “i” is greater than or equal to zero.

The reversed string will be added to the “i” and it will be stored in the reversestr variable.

Later, The if…condition will check whether the input string and the reverse string are equal. If it is equal then it will print “It is a palindrome string”. Otherwise, It will print “It is not a palindrome number” using the else condition.

Finally, The output will show on the result screen using the system.out.printIn() function.

Read Also : Find a Number Is Palindrome Or Not in Java

Note

I have already posted the article about Check If String is Palindrome or Not in JavaScript. If you are looking to learn then please read and learn about it.

Output of Find a String Is Palindrome Or Not in Java

The example output of find a string is palindrome or not in java will be shown below for your reference.

alphaahpla is a Palindrome String.

Final Words

I hope this article helps you to learn the “Find a String is a Palindrome or Not in Java” Program. If you face any issues please let me know via the comment section. Share this article with other Java program developers via social networks. Thank You!

Manoj S

Hi, I'm Manoj working as a part-time blogger in Coding Diksha. Here, I post about programming to help developers.

Leave a Reply