String Palindrome Program in Java
The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and backward (right to left) without changing the meaning of the word or phrase. For example, madam, tattarrattat, noon, civic, racecar, mom, level, etc. In this section, we will create Java programs with different approaches and check the string is palindrome or not.
There are various ways to check whether a string is a palindrome or not. Let’s start with the simple iterative approach using Java-for loop.
Iterative Approach
Filename: PalindromeExample.java
Output:
Explanation: First, we compare the first character with the last character, the second character with the second last character, the third character with the third last character and so on, of the input string. If we found a mismatch anywhere while making the comparison, we can say that the given string is not a palindrome. Otherwise, it is a palindrome.
Two-Pointer Approach
Filename: PalindromeExample1.java
Output:
Explanation: In the above program, we have taken two pointers, namely, ptr1 and ptr2. The first pointer, ptr1, points to the first letter of the input string and the second pointer, ptr2, points to the last character of the input string. Now, we start the comparison of the characters pointed by those two pointers. If at any place a mismatch is found, the loop terminates and prints string is not palindrome. Else, the input string is a palindrome.
Built-in Method Approach
Filename: PalindromeExample2.java
Output:
Explanation: Since the Java String class does not contain the reverse() method, Therefore, we took the help of the Java StringBuilder class. Using the reverse() method of the Java StringBuilder class, we reverse the input string. Finally, we make a comparison between the copy of the original string and its reversed form and displaying the result accordingly.
Recursive Approach
Filename: PalindromeExample3.java
Output:
Explanation: We have used the concept of two pointer approach here. The start and end arguments of the isPalindrome() method point to the first and last character of the given string. If we find a mismatch, we come out from the recursion and return false. If the characters, pointed by the first pointer and the second pointer, match, we move further to explore the next set of characters, and we continue to do so until we reach the base case or find a mismatch.