Sub topic 2
Understand Parameter and Local Variable Scope
Understand Parameter and Local Variable Scope
A parameter is a variable named in a method’s declaration. An argument is the value supplied when the method is called.
A local variable is declared inside a method. Its scope is the part of the code where you can use it. A block is code between braces. A local variable is usually in scope from its declaration to the end of its block. A parameter is available throughout its method body.
In the example below, number and box are parameters of change. The variable next is local to that method. None of them can be used by name in main.
Trace Primitive Values and Object References
A primitive is a basic value, such as an int integer. An object is a value created from a class. A reference is a value that points to an object.
Java passes a copy of each argument to a method. For an object, it copies the reference, not the object. Both references can point to the same object.
Save this program as ScopeDemo.java, then run javac ScopeDemo.java and java ScopeDemo.
class Box {
int value;
}
class ScopeDemo {
private static void change(int number, Box box) {
int next = number + 1;
number = next;
box.value = next;
box = new Box();
}
static int add(int a, int b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
int number = 1;
Box box = new Box();
change(number, box);
System.out.println(number);
System.out.println(box.value);
System.out.println(add(2, 3));
System.out.println(add(2, 3, 4));
}
}The program prints 1, 2, 5, and 9, each on its own line.
Changing the copied number does not change the caller’s variable. But box.value = next changes the shared object. Assigning a new object to the box parameter changes only that copy of the reference.
Control Method Access
An access modifier controls where a method can be used. In the example, change is private, so only code in ScopeDemo can call it.
A package is a group of related Java classes. A subclass is a class that extends another class.
| Modifier | Where the method can be used |
|---|---|
| `private` | Within its declaring class |
| No modifier | Within the same package |
| `protected` | Within the same package and in subclasses, with some limits |
| `public` | From anywhere the declaring class is accessible |
Overload Methods with Different Parameters
Overloading means giving methods the same name but different parameter types or counts. The two add methods take two and three integers. Java selects one based on the arguments.
Changing only a method’s return type does not create an overload.
Exercise
After change(number, box), why is number still 1 but box.value is 2?
Show answer
The method changes a copy of number, but its copied reference points to the same Box object, so it changes that object.