Sub topic 5
Understand Parameter and Local Variable Scope
A variable has a name that you can use to refer to a value. But you cannot use that name everywhere in a Java program. Its scope is the part of the program where the name is available.
Scope helps keep a program clear. A name used inside one method does not have to interfere with the same name used in another method. Scope also helps prevent accidental use of a variable where it does not belong.
This chapter assumes you have seen Java methods, parameters, and basic control flow.
Parameters belong to their method
A parameter is a variable listed in a method declaration. An argument is the value supplied when the method is called.
A parameter is available throughout its method’s body. The body is the code between the method’s opening and closing braces.
A local variable is a variable declared inside a method or another block of code. A block is a group of statements between braces, such as the body of a method or an if statement.
Save this program as ScopeDemo.java. Compile it with javac ScopeDemo.java, then run it with java ScopeDemo.
class ScopeDemo {
static void show(int count) {
int doubled = count * 2;
System.out.println("count: " + count);
if (count > 2) {
String label = "large";
System.out.println(label + ": " + doubled);
doubled = doubled + 1;
}
for (int step = 0; step < 2; step++) {
int result = doubled + step;
System.out.println("step " + step + ": " + result);
}
System.out.println("doubled: " + doubled);
}
public static void main(String[] args) {
int count = 3;
show(count);
}
}The output is:
count: 3
large: 6
step 0: 7
step 1: 8
doubled: 7In show, count is a parameter. It can be used anywhere in the body of show, including inside the if and for blocks.
In main, count is a local variable. The two variables have the same name, but they are in different methods. The count in main is not the parameter in show.
Local variables belong to blocks
In the example, doubled is declared directly inside the body of show. It is available after its declaration, including in the blocks inside that body.
The other local variables have smaller scopes:
labelis declared inside theifblock. It is available only after its declaration and before that block’s closing brace.stepis declared in theforstatement. It is available in the loop’s condition, update, and body, but not after the loop.resultis declared inside the loop body. It is available after its declaration and before that body’s closing brace.
A loop repeats a section of code. On each pass through this loop, Java runs the declaration of result again.
| Name | Where it is available in `show` |
|---|---|
| `count` | Throughout the method body |
| `doubled` | After its declaration, through the rest of the method body |
| `label` | After its declaration, inside the `if` block |
| `step` | In the `for` statement and its body |
| `result` | After its declaration, inside the loop body |
For example, adding System.out.println(label); after the if block would cause an error. At that point, label is out of scope. The same is true of step after the for loop.
Inner blocks can use outer variables
A block inside another block is called an inner block. An inner block can use variables that are already in scope in the outer block.
In ScopeDemo, the if block uses both count and doubled. It also changes doubled:
doubled = doubled + 1;This is the same doubled variable declared earlier in show. Because the assignment happens when count is 3, the later loop sees the changed value, 7.
The rule does not work in reverse. Code outside the if block cannot use label, because label belongs to that inner block.
Declare before use
A local variable is not available before its declaration. In show, for example, doubled cannot be used in a statement placed before int doubled = count * 2;.
A declaration can also give the variable its first value. This is called initialization. The declaration of doubled initializes it to count * 2.
Java lets you declare a local variable first and assign it later. Before you read its value, though, Java must be able to tell that it has been assigned on every possible path to that read. A compiler is the tool that checks Java code and prepares it to run. If a local variable might not have a value, the compiler reports an error.
Save this example as BranchScope.java, then compile and run it.
class BranchScope {
static void report(int score) {
String result;
if (score >= 50) {
String note = "passed";
result = note;
} else {
String note = "not passed";
result = note;
}
System.out.println(result);
}
public static void main(String[] args) {
report(60);
report(20);
}
}The output is:
passed
not passedresult is declared in the method body, so it is still in scope at the final print statement. Both the if and else blocks assign it a value. Therefore, the compiler can tell that it has a value before it is printed.
Each block also declares a variable named note. That is allowed because the two note variables are in separate blocks. Neither is in scope inside the other block, and neither is available after the entire if statement.
If you removed the else block, there would be a path where result is never assigned: a score below 50. The compiler would reject the later attempt to print it. You could fix that by keeping the else block or by giving result an initial value before the if.
Avoid overlapping local names
You cannot declare a local variable with the same name as a parameter or another local variable that is still in scope in an enclosing block.
For example, inside show, a declaration such as int count = 4; would be an error. The parameter named count is already in scope. Putting that declaration inside the if block would not fix it.
Use a different name instead. Names such as count, doubled, and result help show what each variable is for.
A local name can hide a field
A field is a variable declared in a class, outside its methods. A class is a design for objects, and an object holds its own field values.
A parameter or local variable can have the same name as a field. When that happens, the local name shadows the field: the simple name refers to the parameter or local variable within its scope.
Save this program as NameDemo.java, then compile and run it.
class NameDemo {
String name = "Mina";
void greet(String name) {
System.out.println("Parameter: " + name);
System.out.println("Field: " + this.name);
}
public static void main(String[] args) {
NameDemo person = new NameDemo();
person.greet("Ava");
}
}The output is:
Parameter: Ava
Field: MinaInside greet, the simple name name means the parameter. The expression this.name means the field named name on the current object. Here, this refers to the person object whose greet method was called.
Shadowing a field is allowed, but it can be confusing. Use this.name when you mean the field, or choose distinct names when that makes the code easier to read.
Scope is about names
Scope tells you where a name can be used in code. It does not, by itself, say when an object stops being useful. For example, a method can create an object and return it. Another method can then use that object through its own variable, even though the original local variable is no longer in scope.
When you are unsure about a name, find its declaration and its enclosing braces. Then check whether the line you are reading is after the declaration and still inside the right block.
Practice
Exercise
In ScopeDemo, which parameters and local variables are in scope at the final print statement in show?
Show answer
The parameter count and the local variable doubled are in scope. label, step, and result are out of scope.
Exercise
In BranchScope, why can both branches declare a variable named note?
Show answer
Each note is declared in a separate block. The first note is not in scope in the second block.
Exercise
In NameDemo, what do name and this.name refer to inside greet?
Show answer
name refers to the parameter. this.name refers to the field on the current object.