Problem: Write a java program to check whether the given string is palindrome or not.

There are multiple ways to check for a palindrome string in Java. Let’s discuss some of the methods with examples.

Check Palindrome String in Java using for Loop

In this method, we reverse the string using a loop and compare the reverse with the original input string.

To reverse the string we need to loop through each character of the original string from the back and concatenate it into the reverse string.

Output

Enter a String
mom
Palindrome String

Enter a String
wow wow
Palindrome String

Enter a String
pencil programmer
Not a Palindrome String


Check Palindrome String in Java Without Finding its Reverse

To check whether a string or word is palindrome or not without computing reverse, we need to compare 1st half of the string with another half.

We can achieve this by using for loop from 0 to half the length of the input string (i.e. str.length()/2).

Output

Enter a String
madam
Palindrome String

Enter a String
hello!
Not a Palindrome String


Check Palindrome String in Java using StringBuilder

The StringBuilder class in Java has an inbuilt reverse() method, that can be used to reverse a string.

All we need to do is to compare the input string with the return result of the reverse() method.

Here is the Java code for the same.

Output

Enter a String
lol
Palindrome String

Enter a String
please comment
Not a Palindrome String


In this tutorial, we learned different ways to check palindrome string in Java programming language.

Leave a Reply