Java Programming Tutorials

Java programming tutorials with many code examples!

Palindrome detector in Java

Palindrome is a sequence of chars which reads the same backward and forward. Detecting palindrome is a common job interview task therefore we’ll show how to implement that.

Fast Palindrome Detector

This fast algorithm goes through string from both ends and expects them to be the same. As soon as they start to differ we know that this is not a palindrome.

package com.farenda.tutorials.algorithms.strings;

public class PalindromeDetector {

    public boolean isPalindrome(String s) {
        for (int i = 0, j = s.length()-1; i <= j; ++i, --j) {
            // front char != back char
            if (s.charAt(i) != s.charAt(j)) {
                return false;
        return true;

Notice that we compare the chars only to the middle of the string, because after that they start to repeat – remember, palindrome from both sides is the same. ;-)

Slow and easy Palindrome Detector

This implementation is presumably slower than the previous one, but is much more readable and requires no explanation:

public boolean isSlowPalindrome(String s) {
    return new StringBuilder(s).reverse().toString().equals(s);

Unit tests

To check that it really works, let’s write some JUnit tests:

package com.farenda.tutorials.algorithms.strings;

import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class PalindromeDetectorTest {

    private PalindromeDetector detector = new PalindromeDetector();

    public void shouldFindPalindromes() {


    public void shouldDetectNotPalindromes() {
        assertFalse(detector.isPalindrome("random string"));

        assertFalse(detector.isSlowPalindrome("random string"));
Share with the World!