AP Computer Science A · Topic 5.8

Scope and Access Practice

Part of Writing Classes.

Practice questions

13

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

  1. Sample 1difficulty 2/5

    public class Card {
        public String suit;
        private int rank;
        public Card(String s, int r) { suit = s; rank = r; }
    }
    // ...
    Card c = new Card("H", 7);
    System.out.println(c.suit);

    What is printed?

    • A

      H

      check_circle
    • B

      7

    • C

      Compile-time error

    • D

      null

    Why

    suit is public, so it can be accessed from outside the class. It was set to "H".

  2. Sample 2difficulty 3/5

    Local variables in a method

    • A

      Are shared with all instances

    • B

      Persist across method calls

    • C

      Default to 0

    • D

      Only exist while the method is executing

      check_circle

    Why

    Locals live on the stack frame; destroyed when method returns.

  3. Sample 3difficulty 3/5

    Inside a class's instance method, accessing instance field <code>count</code>

    • A

      Cannot access; must use getter

    • B

      this->count

    • C

      Dog.count only

    • D

      count or this.count (both work)

      check_circle

    Why

    Either is valid; <code>this.</code> is mandatory only when shadowed by a parameter.

  4. Sample 4difficulty 3/5

    public class C {
        static int x = 5;
        public static int change() {
            int x = 10;
            x = x + 1;
            return x;
        }
        public static int run() {
            int a = change();
            return a + x;
        }
    }
    // Call: System.out.println(C.run());

    What is printed?

    • A

      16

      check_circle
    • B

      21

    • C

      11

    • D

      22

    Why

    Local x in change() shadows static. change() returns 11. run() returns 11 + 5 (static x unchanged) = 16.

  5. Sample 5difficulty 3/5

    public class Demo {
        private int x = 10;
        public int compute() {
            int x = 5;
            return x;
        }
    }
    // ...
    Demo d = new Demo();
    System.out.println(d.compute());

    What is printed?

    • A

      15

    • B

      10

    • C

      5

      check_circle
    • D

      Compile-time error

    Why

    The local variable x shadows the instance variable inside compute, so the local x with value 5 is returned.