User Oleksandr Miadelets
Oleksandr Miadelets
Head of Developers Team at CodeGym

Java program to check palindrome string

Published in the Random group
Some problems in programming have the status of classic ones. Typically, such tasks are related to mathematics and they are very fond of asking students of Computer Science specialties, as well as job seekers at interviews. They are good because they help to set up your thinking in a programmer way quite well, as well as train it. One of such problems is checking whether a string is a palindrome, and we are going to consider it in this article.

What is a palindrome and why be able to look for them

A palindrome is a number, letter combination, word or text that reads the same in both directions. To summarize, a palindrome can be called any set of characters that is symmetrical about its middle. The word is from Greek roots that literally derive “running back” (palin is “again, back,” and dromos, “running.”). Palindrome in Java means the same as in general meaning. Examples of palindromes:
  • 1881
  • aaqquqqaa
  • pop
  • Noon
  • level
  • Rotator
  • My Gym
  • Madam I am Adam
  • Now, sir, a war is won!
1881 is a palindrome number and the others are palindrome strings. In this article, we'll be looking at palindromes that are represented as strings, but some algorithms are quite applicable to other kinds of palindromes in Java. Why might you want to look for palindromes? In fact, we don't often have to look for palindromes in everyday life. It's kind of a very specific task. If we recall string algorithms, more often in practice, programmers can find searching for a substring in a string, and not searching for palindromes or their number. However, problems related to palindromes have important applications. The first is olympiad programming. There could be tasks to identify palindromes. The second application that is relevant for novice programmers is interviewing. At a technical interview, you may well be asked to quickly write a program to check if a string is palindrome, maybe even on a piece of paper. Well, in science, the most practical application of finding palindromes is biological algorithms. According to Wikipedia, the palindromicity of biological compounds plays an important role in the properties of various biological compounds.

Palindrome algorithm code example

Let's think. A string is a sequence of characters, one might say, an array of char. It would be most logical to follow this sequence from both sides to the middle and compare the extreme characters. If until we reach the middle all our characters will match, then we have a palindrome. Let's create a boolean method validPalindrome(String s) to check if String is palindrome. Java code is here:

public class PalindromeTest1 {

//method to check if a string is palindrome    
public static boolean validPalindrome(String s) {
       for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
           if (s.charAt(i) != s.charAt(j)) {
               return false;
           }
       }
       return true;
   }

   public static void main(String[] args) {
       String s1 = "level";
       String s2 = "cool";
       String s3 = "Madam";
       String s4 = "Now, sir, a war is won!"
       boolean b1 = validPalindrome(s1);
       boolean b2 = validPalindrome(s2);
       boolean b3 = validPalindrome(s3);
       boolean b4 = validPalindrome(s4);
       System.out.println("is " + s1 + " a palindrome? " + b1);
       System.out.println("is " + s2 + " a palindrome? " + b2);
       System.out.println("is " + s3 + " a palindrome? " + b3);
       System.out.println("is " + s4 + " a palindrome? " + b4);


   }

}
In the main method, we check for palindromic strings “level”, “cool”, “Madam” and "Now, sir, a war is won!". As you can see, the first, third and fourth are palindromes, but the second is not. What will the program give?
is level a palindrome? true is cool a palindrome? false is Madam a palindrome? false is Now, sir, a war is won! a palindrome? false
So, the first is a palindrome, the second is not. However, what is wrong with the third and fourth? Why is the result false? You probably already guessed that the point is that some characters in this string are uppercase and some are lowercase, and for Java M and m are two different characters. Let's improve the program to take this difference into account. Here is a program to check if a string is a palindrome that solves upper and lowercase problems.

public class PalindromeTest2 {

   //lowercase and uppercase characters should be treated the same:
   public static boolean validPalindrome(String s) {
       for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
           if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j)))
               return false;
       }
       return true;
   }

   public static void main(String[] args) {
       String s1 = "level";
       String s2 = "cool";
       String s3 = "Madam";
        String s4 = "Now, sir, a war is won!"
       boolean b1 = validPalindrome(s1);
       boolean b2 = validPalindrome(s2);
       boolean b3 = validPalindrome(s3);
       boolean b4 = validPalindrome(s4);
       System.out.println("is " + s1 + " a palindrome? " + b1);
       System.out.println("is " + s2 + " a palindrome? " + b2);
       System.out.println("is " + s3 + " a palindrome? " + b3);
       System.out.println("is " + s4 + " a palindrome? " + b4);


   }

}
This time the result is more predictable for us:
is level a palindrome? true is cool a palindrome? false is Madam a palindrome? true is Now, sir, a war is won! a palindrome? false
Well…not exactly predictable. The situation with “Madam” is getting better, but what with our long and happy palindrome “Now, sir, a war is won!”. It’s quite easy, if you remember that all spaces and punctuation symbols are the same as letters for Java. So we need to improve our algorithm again to correct this oversight. Let's teach our program to ignore spaces and punctuation. Simply put, we ignore all non-alphanumeric characters. Here is the improved palindrome program in Java.

public class PalindromeTest3 {

   //in addition to the above, ignore all non alphanumeric chars like punctuation and spaces
   private static boolean isAlphanumeric(char c) {
       return Character.isAlphabetic(c) || Character.isDigit(c);
   }

   public static boolean validPalindromeIgnorePunctuation(String s) {
       for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
           // skip chars we should ignore
           while (j >= 0 && !isAlphanumeric(s.charAt(j))) j--;
           while (i < s.length() && !isAlphanumeric(s.charAt(i))) i++;
           // overskipped -> nothing left to validate
           if (i >= j) return true;

           if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j)))
               return false;
       }
       return true;
   }


   public static void main(String[] args) {
       String s1 = "level";
       String s2 = "cool";
       String s3 = "Madam";
       String s4 = "Now, sir, a war is won!";
       boolean b1 = validPalindromeIgnorePunctuation(s1);
       boolean b2 = validPalindromeIgnorePunctuation(s2);
       boolean b3 = validPalindromeIgnorePunctuation(s3);
       boolean b4 = validPalindromeIgnorePunctuation(s4);
       System.out.println("is " + s1 + " a palindrome? " + b1);
       System.out.println("is " + s2 + " a palindrome? " + b2);
       System.out.println("is " + s3 + " a palindrome? " + b3);
       System.out.println("is " + s4 + " a palindrome? " + b4);


   }

}
Java program to check palindrome string - 1At least the result is what we expected from it:
is level a palindrome? true is cool a palindrome? false is Madam a palindrome? true is Now, sir, a war is won! a palindrome? true
Perhaps, if you are just starting to program, it is difficult for you to understand how the string traversal and comparison algorithms work. Of course, it is better to deal with this, but you can write a simplified version of the very passage through the array of characters, which in fact is a string. You can use the StringBuffer.reverse method to check if a string is a palindrome. Let's do the simplest version without checking for non-alphanumeric symbols and upper and lowercase.

public class PalindromeTest5 {

   public static boolean validPalindrome(String s) {

       StringBuffer buffer = new StringBuffer(s);
       buffer.reverse();
       String data = buffer.toString();

       if (s.equals(data)) {
           return true;
       }
       return false;
   }
   public static void main(String[] args) {
       String s1 = "level";
       String s2 = "cool";
       String s3 = "Madam";
       String s4 = "Now, sir, a war is won!";
       boolean b1 = validPalindrome(s1);
       boolean b2 = validPalindrome(s2);
       boolean b3 = validPalindrome(s3);
       boolean b4 = validPalindrome(s4);
       System.out.println("is " + s1 + " a palindrome? " + b1);
       System.out.println("is " + s2 + " a palindrome? " + b2);
       System.out.println("is " + s3 + " a palindrome? " + b3);
       System.out.println("is " + s4 + " a palindrome? " + b4);


   }
}
The result is the same as in the very first example
is level a palindrome? true is cool a palindrome? false is Madam a palindrome? false is Now, sir, a war is won! a palindrome? false
If you want, you may improve this program such as we did with the first example.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION