Java Variable Scope

Introduction

Java can declare variables within any block.

A block is begun with an opening curly brace { and ended by a closing curly brace }.

A block defines a scope.

Each time we start a new block, we are creating a new scope.

A scope specifies which objects are visible to which parts of the program.

It also determines the lifetime of those objects.

Java variables declared inside a scope are not visible or accessible to outside scope.

Scopes can be nested.

The objects declared in the outer scope will be visible to code within the inner scope.

Objects declared within the inner scope will not be visible outside it.

The following program illustrates the scope.

// Demonstrate block scope.
public class Main {
  public static void main(String args[]) {
    int x; // visible to all code within main

    x = 10;//from  ww w  .  j a  v a 2s. co m
    if(x == 10) { // start new scope
      int y = 20; // visible only to this block

      // x and y both known here.
      System.out.println("x and y: " + x + " " + y);
      x = y * 2;
    }//new scope ends
    // y = 100; // Error! y not known here 

    // x is still known here.
    System.out.println("x is " + x);
  }
}

Within a block, variables can be declared at any point.

Variable are valid only after they are declared.

Java variables are created when their scope is entered, and destroyed when their scope is left.

In the following code the y is initialized each time block is entered.

// Demonstrate lifetime of a variable.  
public class Main {  
  public static void main(String args[]) {  
    int x;  /*from w  ww .j  a va2s  . c  om*/
  
    for(x = 0; x < 3; x++) {  
      int y = -1; // y is initialized each time block is entered  
      System.out.println("y is: " + y); // this always prints -1  
      y = 999;  
      System.out.println("y is now: " + y);  
    }  
  }  
} 

y is reinitialized to -1 each time the inner for loop is entered.

As Java code blocks can be nested, we cannot declare a variable to have the same name as one in an outer scope.

For example, the following program is illegal:

// This program will not compile
class ScopeErr {
   public static void main(String args[]) {
     int bar = 1;
     {              // creates a new scope
       int bar = 2; // Compile time error -- bar already defined!
     }
   }
}



PreviousNext

Related