OneBite.Dev - Coding blog in a bite size

check if a string is a palindrome in java

Code snippet on how to check if a string is a palindrome in java

public static boolean isPalindrome(String str) {
  int i = 0, j = str.length() - 1;
  while (i < j) {
    if (str.charAt(i) != str.charAt(j)) {
      return false;
    }
    i++;
    j--;
  }
  return true;
}

This code checks if a given string is a palindrome, a word or phrase that is the same when read backwards. To do this, it uses two indexes, one from the beginning and one from the end, and it moves them together until they meet in the middle. At each step it checks if the characters at both indexes are the same. If they are, it moves on to the next pair of characters. If they are not the same, it returns false. If all the characters are the same when read forwards and backwards, the complete string is a palindrome and it returns true.

java