Scope and
Access
Understand how variables are visible across different parts of a Java program, and how access modifiers control what code can use them.
What Is Scope?
Scope is the region of a program where a declared variable or method can be referenced. If you try to use a name outside its scope, the compiler produces an error: the name simply does not exist in that context.
Three Levels of Scope
Scope Visualized
Why Scope Matters
Access Modifiers in Java
Access modifiers are keywords placed before a class member declaration to control who can use that member. On the AP exam, you need to know two:
public vs private in Action
Local vs Instance Variables
| Local Variable | Instance Variable | |
|---|---|---|
| Declared in | A method or block | A class (outside methods) |
| Scope | Method / block only | Entire class |
| Default value | None: must initialize | 0, false, or null |
| Access modifier | Not allowed | private (recommended) |
| Lifetime | Until method returns | Until object is garbage-collected |
The this Keyword
When a local variable has the same name as an instance variable, the local variable shadows (hides) the instance variable. Use this to refer to the instance variable explicitly.
How to Apply Scope Rules
Example 1: Variable Visibility
Example 2: Block Scope in Loops
Example 3: Shadowing Pitfall
After new Rect(5), the instance variable width is still 0 (the default for int). The parameter shadows the instance variable.
The Encapsulation Pattern
The AP CS A exam expects you to follow this pattern for every class:
Common Mistakes
Scope and Access Summary
| Class-Level | Method-Level | Block-Level | |
|---|---|---|---|
| Keyword | private / public | None | None |
| Visibility | Whole class | One method | One { } block |
| Default value | Yes (0 / null) | No | No |
| Typical use | Object state | Temporary calculations | Loop counters |
| Lifetime | Object lifetime | Method call | Block execution |
Question 1 of 5
Consider the following code:
public class Box {
private int size;
public void grow() {
int amount = 3;
size += amount;
}
public void shrink() {
size -= amount;
}
}
What happens when you try to compile this class?
Question 2 of 5
Which access modifier should be used for instance variables according to AP CS A best practices?
Question 3 of 5
Consider the following constructor:
public class Car {
private String color;
public Car(String color) {
color = color;
}
public String getColor() {
return color;
}
}
What does new Car("red").getColor() return?
Question 4 of 5
Consider the following code:
public void mystery() {
for (int k = 0; k < 5; k++) {
int sum = 0;
sum += k;
}
System.out.println(sum);
}
What is the result of calling mystery()?
Question 5 of 5
Consider two classes:
public class Account {
private double balance;
public double getBalance() { return balance; }
}
public class Bank {
public void check(Account a) {
System.out.println(a.balance);
}
}
What happens when the Bank class is compiled?