Scope and Lifetime : Variables in Java Programming Language

The Scope and Lifetime of Variables :

  1. We can declare variables within any block.
  2. Block is begun with an opening curly brace and ended by a closing curly brace.
  3. 1 block equal to 1 new scope in Java thus each time you start a new block, you are creating a new scope.
  4. A scope determines what objects are visible to other parts of your program. It also determines the lifetime of those objects.

Live Example 1 : Variable Scope in Java Programming

// Demonstrate block scope.
class Scope {
  public static void main(String args[])
  {
  int n1; // Visible in main
  n1 = 10;
  if(n1 == 10)
   {
   // start new scope
   int n2 = 20; // visible only to this block
   // num1 and num2 both visible here.
   System.out.println("n1 and n2 : "+ n1 +""+ n2);
   }
   // n2 = 100; // Error! y not known here
   // n1 is still visible here.
    System.out.println("n1 is " + n1);
  }
}

Output :

n1 and n2 : 10 20
n1 is 10
  1. n1 is declared in main block thus it is accessible in main block.
  2. n2 is declared in if block thus it is only accessible inside if block.
  3. Any attempt to access it outside block will cause compiler time error.
  4. Nested Block can have access to its outermost block. [if block is written inside main block thus all the variables declared inside main block are accessible in if block]

Live Example 2 : How we get Compile Error

class ScopeInvalid {
  public static void main(String args[]) {
    int num = 1;
    {              // creates a new scope
      int num = 2; // Compile-time error
                   // num already defined
    }
  }
}

will cause compile error because variable “num” is declared in main scope and thus it is accessible to all the innermost blocks. However we can try this -

class ScopeInvalid {
  public static void main(String args[]) {
    {              // creates a new scope
      int num = 1;
    }
    {              // creates a new scope
      int num = 2;
    }
  }
}

Live Example 3 : Re Initializing Same Variable again and again

class LifeTime {
  public static void main(String args[]) {
    int i;
    for(i = 0; i < 3; i++) {
      int y = -1;
      System.out.println("y is : " + y);
    }
  }
}

Output :

y is : -1
y is : -1
y is : -1
  1. Variable “y” is declared inside for loop block.
  2. Each time when control goes inside “For loop Block” , Variable is declared and used in loop.
  3. When control goes out of the for loop then the variable becomes inaccessible.