Scope and Passing By Value

Scopes of variables

In Java, when you declare a variable, the variable has an associated scope: the region of code for which that variable and its value are accessible. Specifically, the scope of a variable is determined by the block of code in which the variable is declared. Here, a block is a section of code contained between an opening curly brace { and its closing curly brace }

Consider the following simple (useless) class, ScopeTest:

public class ScopeTest {
  private static int a = 1;

  public static void main(String[] args) {
    int b = 2;
    if (b == 2) {
      int c = 3;
    }
  } 
}

Within the class ScopeTest there are 3 different scopes: scope 1 the scope between lines 1 and 10, where int a is declared, scope 2 between lines 4 and 9 within the main method where int b is declared, and scope 3 between lines 6 and 8 where int c is declared. 

Each variable is accessible only within its scope. For example, the following modification of ScopeTest will result in an error: 

public class ScopeTest {
  private static int a = 1;

  public static void main(String[] args) {
    int b = 2;
    if (b == 2) {
      int c = 3;
    }
    b = c; // ERROR: c was not declared in this scope!
  } 
}

Notice that the three scopes in ScopeTest are nested: the scope of c is contained within the scope of b which is contained within the scope of a

Now for a bit of a behind-the-scenes view of what Java is doing with these variables. When your code is executing, Java maintains a table of variable names and their corresponding values for each scope separately. When a statement uses the value of a variable, Java first checks the innermost scope containing the statement for the required variable name/value. If the variable was not declared in the innermost scope, it then checks the next larger scope. This process continues until the outermost scope is reached. (You will get an error if the variable name is not found in any scope.)

For example, consider the following code:

public class ScopeTest {
  private static int a = 1;

  public static void main(String[] args) {
    int b = 2;
    if (b == 2) {
      int c = 3;
      System.out.println("a = " + a);
    }
  } 
}