String Objects: Concatenation, Literals, and More

AP Computer Science A· difficulty 3/5

String s = "hi";
if (s.charAt(0) == "h") {
    System.out.println("starts with h");
}

What is wrong?

  • A

    charAt returns a char; compare with 'h', not "h"

    check_circle
  • B

    charAt cannot be called on a String

  • C

    Nothing is wrong

  • D

    The if-statement needs braces

Explanation

A char literal uses single quotes ('h'). Comparing a char to a String literal is a type-mismatch compile error.

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

Related questions