OCA Java SE 8 Building Blocks - Variable Scope








The rules on scope

  • Local variables are in scope from declaration to end of block.
  • Instance variables are in scope from declaration until object garbage collected.
  • Class variables are in scope from declaration until program ends.

Local Variable

The local variables are declared within a method.

There are two local variables in the following method.

myValue is declared inside the method.

myPara is called a method parameter. It is also local to the method.

Both of these variables have a scope local to the method. This means they cannot be used outside the method.

public void eat(int myPara) { 
  int myValue = 1; 
} 

Local variables can never have a scope larger than the method they are defined in.

Local variables can have a smaller scope as follows.

3: public void myMethod(boolean checked) { 
4:  if (checked) { 
5:   int myValue = 1; 
6:  }  // myValue goes out of scope here 
7:  System.out.println(myValue);// DOES NOT COMPILE 
8: } 

checked has a scope of the entire method.

myValue has a smaller scope. It is only available for use in the if statement because it is declared inside of it.

A set of braces {} in the code creates a new block of code.

Each block of code has its own scope.

When there are multiple blocks, we can match them from the inside out.

The blocks can contain other blocks. The inner blocks can reference variables defined in the outter blocks, but not vice versa.





Note

For example:

public void myMethod(boolean checked) { 
  if (checked) { 
    int myValue = 1; 
    {  
       boolean myBoolean = true;  
       System.out.println(myValue);  
    } 
  } 
  System.out.println(myBoolean);  // DOES NOT COMPILE 
}