Recursion

AP Computer Science A· difficulty 4/5

public static boolean isPal(String s) {
    if (s.length() <= 1) return true;
    if (s.charAt(0) != s.charAt(s.length() - 1)) return false;
    return isPal(s.substring(1, s.length() - 1));
}
System.out.println(isPal("racecar"));

What is printed?

  • A

    true

    check_circle
  • B

    false

  • C

    Compile-time error

  • D

    Runtime error

Explanation

"racecar" reads the same forward and backward; recursion strips outer chars until base case.

Want 10 more like this — adaptive to your weak spots?

Related questions