AP Computer Science A · Topic 2.1

Objects: Instances of Classes Practice

Part of Using Objects.

Practice questions

9

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 9 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. Sample 1difficulty 2/5

    Which is a reference (object) type in Java?

    • A

      boolean

    • B

      String

      check_circle
    • C

      int

    • D

      double

    Why

    <code>String</code> is a class. Objects are stored by reference.

  2. Sample 2difficulty 3/5

    public class Holder {
        private int n;
        public Holder(int n) { this.n = n; }
        public int getN() { return n; }
        public void setN(int n) { this.n = n; }
    }
    // ...
    Holder a = new Holder(1);
    Holder b = a;
    b.setN(42);
    System.out.println(a.getN());

    What is printed?

    • A

      0

    • B

      1

    • C

      42

      check_circle
    • D

      Compile-time error

    Why

    a and b refer to the same object; modifying via b is visible via a.

  3. Sample 3difficulty 3/5

    String[] names = new String[3];
    System.out.println(names[0].length());

    What happens when this code runs?

    • A

      NullPointerException because names[0] is null

      check_circle
    • B

      Prints 0

    • C

      Prints empty string

    • D

      Compile error

    Why

    A new String[] is filled with null references. Calling .length() on null throws NullPointerException.

  4. Sample 4difficulty 3/5

    Calling a method on a <code>null</code> reference causes

    • A

      Returns null

    • B

      Compile error

    • C

      Returns 0

    • D

      Throws NullPointerException at runtime

      check_circle

    Why

    <code>String s = null; s.length();</code> → NPE at runtime.

  5. Sample 5difficulty 3/5

    What is the default value for an uninitialized object reference (instance field)?

    • A

      Empty string

    • B

      null

      check_circle
    • C

      false

    • D

      0

    Why

    Reference types default to <code>null</code>.