Search code examples
javapalindrome

Check if string is a palindrome


for (int i = 0; i <= (line.length()/2); i++) {  \\loops from the first character until the character in the middle
    if (line.charAt(i) != line.charAt(line.length() - i)) {  \\checks if 1st character of line is not equal to the last character, and so on..
        System.out.println("Entered string is not a palindrome.");
        return; \\ends program, no need to check anything else
    }
}
System.out.println("Entered string is a palindrome.");

I keep getting an index out of range error


Solution

  • An index out of range error is exactly what it says. Valid indexes in Java Strings (also arrays or collections) range from 0 through length() - 1. When you subtract i from line.length(), you can still get line.length(), which is out of bounds, if i is 0. This is an off-by-one error.

    Subtract 1 more from the second character's index to stay in bounds.

    if (line.charAt(i) != line.charAt(line.length() - i - 1)) {