Scope of Variables in Java

Area of a java program where a variable is accessible is called scope of that variable.
Following are important levels of java variable scope:

  1. Method Level Scope
  2. Block Level Scope
  3. Class Level Scope

Method Level Scope

Variable defined in a function can be accessible within that function only. It cannot be called or accessed from outside of that function.

Block Level Scope

Variable defined within a block of curly braces can only be accessed from within this block. It cannot be accessed from outside of that block. However variable defined in a function can be be accessed from any block of a curly braces present in that function provided the block of curly braces is defined after definition of variable. Following example shows an example of block level scope variable:


public class Main {
void display_numbers() {
int size = 50 ;
for( int index = 1; index< size ; index++){
// size is visible here
}
// index is not visible here
// size is visible here
}
}

A block cab of a function, an if statement, else part of if statement, a switch statement, a for loop , a while or do-while loop.

Class Level Scope

Variables declared inside a class but outside of class functions are accessible in class function and outside of class depending access specifier of variable. We will discuss class level scope in detail in later section of this tutorial.