Comparing Objects

AP Computer Science A· difficulty 2/5

public static boolean isHello(String s) {
    if (s == "hello") {
        return true;
    }
    return false;
}

What is wrong with this method?

  • A

    The if-statement is missing braces

  • B

    The method should return s instead of true

  • C

    Nothing is wrong; it works correctly for all inputs

  • D

    Strings should be compared with .equals, not ==

    check_circle

Explanation

== compares object references for Strings, not contents. Use s.equals("hello") to compare characters; == may succeed for literals due to interning but fails generally.

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

Related questions