Java Algorithms How to - Check if a word is a palindrome








Question

We would like to know how to check if a word is a palindrome.

Answer

/*from  w  ww  . ja va 2  s .  c  o m*/
public class Main {
  public static void main(String[] args) {
    String n = "level";
    boolean right = true;
    int f = n.length() - 1;
    for (int i = 0; i < n.length(); i++) {
      if (n.charAt(i) != n.charAt(f - i)) {
        right = false;
      }
    }
    System.out.println("The word is " + right);
  }
}

The code above generates the following result.