3.8 Scope and Access
💻AP Computer Science A Unit 3 Review
3.8 Scope and Access
💻 AP Computer Science A
Scope tells you where a variable can be used in your code. Local variables, including parameters, only exist inside the block where they are declared, and if a local variable or parameter shares a name with an instance variable, the local one is used inside that method or constructor. For AP Computer Science A, use scope rules to identify which variable a name refers to and whether code will compile.
Scope rules also come up when you need to fix errors caused by using a variable outside its block, so you should know where each variable has to be declared for the code to work.
Where Local Variables Live and Which Name Wins
- Local variables are declared in the header or body of a block (like a method, constructor, loop, or
ifblock) and can only be used inside that block. - Parameters to methods and constructors are local variables, so they only exist inside that method or constructor.
- You cannot put
publicorprivateon a local variable. Those keywords are for class members, not locals. - When a local variable or parameter has the same name as an instance variable, the name refers to the local variable inside that method or constructor.
- A variable declared inside a loop or
ifblock is gone once that block ends, so trying to use it outside causes a compile error. - Different methods can reuse the same local variable name because each method has its own scope.
Core Ideas of Scope and Access
Local Variables and Blocks
| Nested-code scope figure |
|---|
┌─ METHOD BLOCK: demonstrateScope() { |
A block is a section of code, usually marked by curly braces. Methods, constructors, loops, and if statements all create blocks. A local variable is any variable declared in the header or body of a block, and it can only be accessed inside that block.
</>Javapublic class ScopeExample { private String instanceVariable = "I'm accessible in all instance methods"; public void demonstrateScope() { // Local variable: only exists in this method String localVariable = "I only exist in this method"; System.out.println(instanceVariable); // OK: instance variable System.out.println(localVariable); // OK: local variable // Block scope: variable inside an if block if (localVariable.length() > 0) { String blockVariable = "I only exist inside this if block"; System.out.println(blockVariable); // OK here } // System.out.println(blockVariable); // ERROR: out of scope // The loop variable i only exists inside the loop for (int i = 0; i < 5; i++) { System.out.println("Iteration " + i); // OK: i is in scope } // System.out.println(i); // ERROR: i is out of scope } public void anotherMethod() { // Each method has its own local scope, so reusing the name is fine String localVariable = "I'm a different local variable"; System.out.println(localVariable); // OK System.out.println(instanceVariable); // OK } }
A few rules to remember:
- A variable declared in a loop header (like
iin aforloop) is only in scope for that loop. - A variable declared inside an
ifblock disappears once the block ends. - Reusing a local variable name in a different method is allowed because each method has its own scope.
Parameters Are Local Variables
Parameters to a method or constructor count as local variables. They only exist inside that method or constructor, and you cannot put an access keyword on them.
</>Javapublic class ParameterScope { private int instanceValue = 42; // number, text, and flag are local to this method public void useParameters(int number, String text, boolean flag) { System.out.println(number); System.out.println(text); System.out.println(flag); // Parameters can be used in nested blocks if (flag) { String message = "Value is " + number; System.out.println(message); } } }
Because parameters are local variables, writing public int number or private String text in a method header would not compile. Access keywords like public and private belong to class members, not to local variables.
When Names Collide: Local Wins
If a local variable or parameter has the same name as an instance variable, the name refers to the local variable inside that method or constructor. The instance variable is still there, but the plain name points at the local one.
</>Javapublic class ShadowingExample { private String name = "Instance variable"; public void demonstrate() { // This local variable has the same name as the instance variable String name = "Local variable"; System.out.println(name); // Prints "Local variable" System.out.println(this.name); // Prints "Instance variable" } // A parameter with the same name as the instance variable public void setName(String name) { // Plain "name" is the parameter; this.name is the instance variable this.name = name; } }
This is the most common spot where scope causes bugs. If you write name = name; inside setName, you are just assigning the parameter to itself and the instance variable never changes. Using this.name to point at the instance variable fixes it. The this keyword is covered more in topic 3.9, but the key idea here is that the unqualified name always refers to the local variable when there is a name collision.
Tracing Variable Names and Spotting Out-of-Scope Errors
Code Tracing: When you trace code, figure out which variable each name refers to before you predict output.
- If a name matches both a local variable and an instance variable, the local variable wins inside that method or constructor.
- A plain name (no
this.) inside a method points at the closest local declaration with that name. - A
this.fieldreference always points at the instance variable, even when a local variable shares the name.
Common Trap: Watch for variables used outside their block. If a question shows a loop variable or a variable declared inside an if block being used after the block ends, that code does not compile. These often appear in questions asking you to explain why a code segment will not work.
Free Response: When you write a class, parameters often share names with the instance variables they initialize. Use this.field = parameter inside constructors and mutator methods so you actually update the object's state instead of assigning a parameter to itself. Keep instance variables private and access them by name (or this.name) inside your own methods.
Common Misconceptions
- Misconception: You can mark a local variable as private.Actually: You cannot.
publicandprivateonly apply to class members like instance variables, constructors, and methods, not to local variables or parameters. - Misconception: A name collision overwrites the instance variable.Actually: It does not. The instance variable still exists; the plain name just refers to the local variable inside that method. You can still reach the instance variable with
this.name. - Misconception: A loop variable is available after the loop.Actually: It is not. A variable declared in a loop header or inside any block is gone once that block ends.
- Misconception: Two methods can't use the same variable name.Actually: They can. Each method has its own scope, so the same local name in different methods refers to separate variables.
- Misconception: Changing a parameter changes the instance variable with the same name.
Related AP Computer Science A Guides
Practice Questions for 3.8
1 of 10
A MathGame class uses a maximum score limit of 999 to determine when a player wins. This limit is the same for all games and never changes. The limit is only used internally by the MathGame methods to check for a win condition and should not be accessible to other classes. Which declaration is most appropriate?
A.
private static int MAX_SCORE_LIMIT = 999;
B.
public static final int MAX_SCORE = 999;
C.
private final int MAX_SCORE_LIMIT = 999;
D.
private static final int MAX_SCORE = 999;
Vocabulary
The following words are mentioned explicitly in the AP® course framework for this topic.Term | Definition |
|---|---|
block of code | A section of code enclosed in braces that defines a region where variables can be declared and accessed. |
instance variable | A variable that belongs to an object and can be accessed throughout the class, as opposed to a local variable that is limited to a specific block of code. |
local variables | Variables declared in the headers or bodies of blocks of code that can only be accessed within the block in which they are declared. |
parameters | Variables that allow procedures to be generalized and reused with a range of input values or arguments. |
scope | The region of code in which a variable can be accessed and used. |
See Fiveable more often in Google
Mark Fiveable as a preferred source and Google is more likely to show you our guides in Top Stories, with a "preferred" badge in AI Mode and AI Overviews.