Check if String is Palindrome in Java

A Palindrome is a word, number, or any other sequence that can be read the same way backward as forwards. There are a couple of ways to check if String is Palindrome in Java.

In this tutorial, we will explore the following:

  • Using StringBuilder class
  • Using the for loop

Check if String is Palindrome in Java using the StringBuilder class

We can use the reverse() method from the StringBuilder class to check if the String is the same backward and forwards.

Example

public class Test {

  public static void main(String[] args) {

    String str = "racecar";

    System.out.println(str.equals(new StringBuilder(str).reverse().toString()));
  }
}
Output: true
 
We can do the same with the StringBuffer class since it also has the reverse() method.

Using the for loop

Here is the example program of using the for loop to check if String is the same backward and forwards:

public class Test {

  public static void main(String[] args) {

    String str = "racecar";

    char[] chars = str.toCharArray();

    for (int i = 0, j = chars.length - 1; j > i; i++, j--) {
      if (chars[i] != chars[j]) {
        System.out.println("String is not palindrome!");
      }
    }

    System.out.println("String is palindrome!");

  }
}
Output: String is palindrome!
 
That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *