Java - Scope and Lifetime of Variable

Java - Scope and Lifetime of Variable

  • Variables are declared anywhere inside a class or a method block which contains an opening curly brace and a closing curly brace.
  • Each block is termed as a new scope.
  • Scope decides on object’s visibility to other parts of the program.
  • Code logic determines the types of variables required for the current program.
  • Lifetime mentions the time that the variable can be used. For example, 
        local variable resides within its method, global variable resides for lifetime of the class, and instance variable last for its lifetime. 

  1. Here the scope of the static variable num1 and instance variable num2 lasts till the end of scope of the class “Counter”
  2. The scope of byte variable a stays closed inside the scope of the method main, that is all the loops or blocks inside main method can access the variable a.
  3. The scope of variable remains only inside the while loop and cannot be accessed outside of the loop.

Sample Code :

class VariableScopeLifetime
	public static void main(String args[]) 
             System.out.println("\n\nWikiTechy -Scope and Lifetime of  Variables\n");  
		int a = 20;
		if(a == 20) 
			int b = 30; 
		System.out.println("Values of a and b: " + a + " " + b);
a = b * 2; System.out.println("Values of a and b: " + a + " " + b);
} System.out.println("Value of a: " + a);
} }

Code Explanation :

    Scope of class “VariableScopeLifetime” starts here.

    Scope of main method starts here.

    Lifetime of variable “a” starts here.

    Scope of if block starts here.

    Lifetime of variable “b” and if block ends here.

    Lifetime of variable “a” and main method ends here.

Output :

  • Hence the output of lifetime variables has been executed successfully.