Java Palindrome String
Java Palindrome String
In this tutorial, we shall check if a string is palindrome in two ways. Firstly, by reversing the string and
comparing it with the original value. Secondly, we shall traverse through string characters from start and end of
the string, and kind of meet in the middle, checking if the characters have equal value.
In the following example, we shall reverse the given string in Java using StringBuilder, and compare it with its
original value. If both are equal, then we can say that the given string is a palindrome.
PalindromeString.java
/**
* Java Program - Check if String is Palindrome
*/
Output
tattarrattat is Palindrome.
tattarrattat is Palindrome.
Instead of reversing the string and checking for equality, we can check if the first and last characters are equal
and progress to the middle of the string. If at any point, the characters are not equal, then it is not a palindrome.
Algorithm
We shall implement following algorithm in Java and write a program to check if given string is palindrome.
1. Start.
2. Take string in str. We need to check if this is palindrome string or not.
3. Take a boolean variable isPalindrome to store if the string is palindrome or not. Initialize it with true .
4. Initialize variable i with 0 .
5. Check if i is less than half the length of string str. If yes, go to step 6, else go to step 8.
6. Check if character in str at index i is equal to that of at length-1-i . If not set isPalindrome to false
and go to step 8.
7. Increment i. Go to step 5.
8. Based on the value of isPalindrome, print the result.
9. Stop.
PalindromeString.java
/**
* Java Program - Check if String is Palindrome
*/
Output
tattarrattat is Palindrome.
Conclusion
In this Java Tutorial, we have written Java program using different techniques on how to check if given string is
a palindrome or not.
Java Examples
✦ Java Tutorial
✦ Reverse a Number
✦ Factorial of Number
Array Examples