AP Computer Science A · Topic 3.7

Comparing Objects Practice

Part of Boolean Expressions and if Statements.

Practice questions

6

Want a predicted score for the whole AP CSA exam? Take the 20-question diagnostic and Lumi will plan the rest.

Sample questions

5 of 6 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. Sample 1difficulty 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

    Why

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

  2. Sample 2difficulty 4/5

    To check if <code>String s</code> equals <code>"yes"</code>, use

    • A

      s.equals("yes")

      check_circle
    • B

      s.compareTo("yes")

    • C

      s == "yes"

    • D

      s == 'yes'

    Why

    Use <code>.equals</code> for string content comparison; <code>==</code> only checks references.

  3. Sample 3difficulty 4/5

    For <code>String a = new String("hi"); String b = new String("hi");</code> — what is <code>a == b</code> and <code>a.equals(b)</code>?

    • A

      == true; equals false

    • B

      Both false

    • C

      Both true

    • D

      == false; equals true

      check_circle

    Why

    <code>==</code> compares references (different objects → false); <code>.equals</code> compares content (same content → true).

  4. Sample 4difficulty 4/5

    Why is <code>if (0.1 + 0.2 == 0.3)</code> unreliable?

    • A

      Always works

    • B

      Round-off error in floating-point representation

      check_circle
    • C

      0.1 isn't a valid number

    • D

      Doubles can't be compared

    Why

    Binary FP cannot represent 0.1 exactly; 0.1+0.2 = 0.30000000000000004.

  5. Sample 5difficulty 4/5

    <code>s.equals(null)</code> (where s is non-null) returns

    • A

      Throws NullPointerException

    • B

      true

    • C

      false

      check_circle
    • D

      Compile error

    Why

    Equals returns false for null comparison; doesn't throw.