TOPIC 3.8 · STUDY

Scope and Access

Scope limits where a name can be used. A local variable or parameter exists only inside its method or block and cannot be declared public or private. A primitive parameter is a separate copy, so changing it does not change the caller's variable unless the method returns the new value. private instance variables are not visible by name from another class; public methods are the access path.

3.8.A

Scope and access

Every variable name has a scope: the region of code where that name can be used. A local variable or parameter lives only inside the method that declares it. A name declared inside an if, while, or for block exists only in that block. After the block or method ends, the name is gone. Local variables and parameters also cannot be declared public or private.

When a caller passes a primitive to a method, the parameter is a separate copy of that value. Updating the parameter changes only the copy. The caller's variable stays the same unless the method returns a new value and the caller stores it.

public static int boost(int n)
{
    n = n + 5;
    return n;
}

int wait = 3;
int shown = boost(wait);
System.out.print(wait + " " + shown);

boost receives a copy of 3 in n, adds 5 so n becomes 8, and returns 8. wait is a different variable and still holds 3. The print is 3 8. If boost did not return n, the caller would have no way to see the updated copy.

After boost finishes, the caller's wait is still 3 while the parameter n holds 8. The two boxes are separate variables.

After the method runs, wait stays 3 on the caller side while n is 8 inside the method. Changing the parameter does not rewrite the caller's variable.

Inside a class, a local name can shadow an instance variable with the same simple name. The local or parameter wins for that name until the method or block ends. A private instance variable cannot be used by name from another class. Other classes reach that data only through public methods the owning class provides.

Key points

  • A local variable or parameter exists only inside its method or block.
  • Local variables and parameters cannot be declared public or private.
  • A primitive parameter is a copy; n = n + 5 does not change the caller's variable.
  • Return the new value if the caller should store an updated result.
  • A local or parameter can shadow an instance variable with the same name.
  • private instance variables cannot be used by name from another class; public methods are the access path.

private fields are not visible by name outside the class.

Practice this topic