Example Java String palindrome checker program using recursion
How to write a Java palindrome program for Strings
To write a Java String palindrome program, follow these steps
- Obtain the text String to check through a literal declaration or user input
- Declare a boolean property to indicate if the Java String is a palindrome
- Evaluate corner cases such as the String being null, a single character or zero characters
- Compare the first character to the last character in the string. If they are not equal, return false.
- Move forward and backwards one character at a time and repeat this comparison
- If the loop never generates a false value, then the Java String is a palindrome
- If the loop does generate a false value, the Java String is not a palindrome
Recursive Java palindrome program example
Here is an example of a recursive Java palindrome program that checks String literals.
package com.mcnz.palindrome.example; public class JavaStringPalindromeProgram { /* The main method declares three Strings for the Java palindrome program to check. */ public static void main(String[] args) { boolean flag = javaPalindromeCheck("sitonapanotis"); System.out.println(flag); flag = javaPalindromeCheck("nine"); System.out.println(flag); flag = javaPalindromeCheck("amanaplanacanalpanama"); System.out.println(flag); } /* This method does a recursive Java palindrome check */ public static boolean javaPalindromeCheck(String s){ if(s.length() == 0 || s.length() == 1) { return true; } if(s.charAt(0) == s.charAt(s.length()-1)) { return palindromeCheck(s.substring(1, s.length()-1)); } return false; } /* End of Java String palindrome checker method */ } /* End of Java palindrome program */
Example Java palindrome checker results
When this program runs, it returns:
- true for sitonapanotis
- false for nine
- true for amanaplanacanalpaname
Other Java Strings to palindrome check
Here are 10 other text Strings the Java palindrome checker program should return a true value for. Put these into your code and test them:
- Do geese see God?
- radar
- No lemon, no melon.
- peep
- Hannah
- Able was I, ere I saw Elba.
- Taco cat
- Never odd or even
- Madam, I’m Adam.
- Red rum, sir, is murder
Note that with these examples, your Java palindrome program will need to decide if it will ignore non-text characters and punctuation, which will add to the complexity of the program.
Java palindrome with loops and arrays
This Java palindrome example uses recursion, which is an advanced concept.
There are also drawbacks to recursion, as it can place a heavy load on the Java stack and eventually trigger a StackOverflowError and terminate your program
Other approaches to solve the Java String palindrome problem include the use of loops and arrays.
Test your skills and see if you can implement your own Java palindrome program with loops, arrays and maybe even the Scanner class to dynamically generate input from the user.