Check if a string is a palindrome in Java

Write a Java program that determines if the given string is palindrome or not.

Java Program to Check if a string is a palindrome

public final class Strings {

    public static boolean isPalindrome(String str) {

        if (str == null || str.isBlank()) {
            // or throw IllegalArgumentException
            return false;
        }

        int left = 0;
        int right = str.length() - 1;

        while (right > left) {

            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }

            left++;
            right--;
        }

        return true;
    }
}

Test

public class Main {

    private static final String TEXT = "ABCDEFEDCBA";

    public static void main(String[] args) {

        boolean resultV1 = Strings.isPalindrome(TEXT);
        System.out.println("'" + TEXT + "' is palindrome? " + resultV1);
    }

}

Output:

'ABCDEFEDCBA' is palindrome? true

Comments