AP Computer Science A · Topic 5.8
Scope and Access Practice
Part of Writing Classes.
Practice questions
13
Sample questions
5 of 13 — sign in to practice the rest with adaptive difficulty and mastery tracking.
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?
- Acheck_circle
H
- 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".
- A
Sample 2difficulty 3/5
Local variables in a method
- A
Are shared with all instances
- B
Persist across method calls
- C
Default to 0
- Dcheck_circle
Only exist while the method is executing
Why
Locals live on the stack frame; destroyed when method returns.
- A
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
- Dcheck_circle
count or this.count (both work)
Why
Either is valid; <code>this.</code> is mandatory only when shadowed by a parameter.
- A
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?
- Acheck_circle
16
- B
21
- C
11
- D
22
Why
Local x in change() shadows static. change() returns 11. run() returns 11 + 5 (static x unchanged) = 16.
- A
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
- Ccheck_circle
5
- D
Compile-time error
Why
The local variable x shadows the instance variable inside compute, so the local x with value 5 is returned.
- A