DEV Community

Aldo Telese
Aldo Telese

Posted on • Updated on

A Simple Way to Check if a Word is Palindrome in Java

Racecar, Civic, Radar, Level, Kayak.

What do all these words have in common?
Try to read them backwards... did you notice anything? Of course you did!

A palindrome word is a word that reads the same backwards as forwards.

The scope of this article is to illustrate you a very simple yet effective way to recognize a palindrome word, using Java.

Let's first create a Palindrome class with a main method and an input string from above:

Image description

What we want now is to pass our input string to a method that will return a boolean: true if the word is palindrome, false otherwise.
We'll make this method static:

Image description

The logic we are going to use is very straightforward: we will divide the length of the input string by 2, and iterate over the string both forwards and backwards to compare, at each iteration, the couple of characters that we find. We will do that as many times as the number we obtained from the previous division.
What if the length is odd? We will round it down!

Let's pick for example the word kayak:
the length is 5. Dividing 5 by 2 will give us 2.5, namely 2 (we always round it down).
Since the result of the division is 2, we will do 2 iterations. At each iteration, we compare the two characters to the left and to the right of our string. If the two characters are not the same, it means the word is not a palindrome and we return false.
If the whole loop terminates without returning false, then we return true: the word is a palindrome.

Here is the code:

Image description

Note: in the case of a string with an odd length, just as in our example, the middle character will not be compared to anything, since there is no need to do so.
In our example, the code executed two iterations:

  • in the first iteration, character at index 0 ("k") was compared with character at index 4 ("k")
  • in the second (and last) iteration, character at index 1 ("a"), was compared with character at index 3 ("a").

An additional iteration would have compared the character at index 2 with itself, which is not needed. Therefore, the code we wrote makes the loop stop before this unnecessary computation.

Please remember to pay attention to case and word separators (in case of sentences). If we used Kayak as our input string, then the method would have returned false as "K" and "k" are different. The same applies when using sentences with whitespaces and punctuation, as they will affect the result. In these cases you need to take into account such additional elements, depending on the specific requirements.

Hope you found this article useful!
See you soon, and keep coding!

Top comments (0)