Check if String is a Palindrome

Description: Determines if the given string is a palindrome by comparing each letter with the corresponding one at the end. This is done in place and returns false if the string is empty.
Tested Platform: Java SE 19, Windows 10
Language: Java
public boolean isPalindrome(String str) {
    boolean palindrome = false;
    str = str.toLowerCase();

    // Loop from the start and end and compare the letter from the front to the one from the end.
    // Once the start is equal to or greater than the end, and it hasn't returned false, it must be a palindrome.
    for (int i = 0, j = str.length() - 1; i < str.length(); i++, j-- ) {
        if (i < j) {
            if (str.charAt(i) != str.charAt(j)) {
                return false;
        else { return true; }
    return palindrome;

Posted: March 20, 2023

Return to the snippets listing