6.4. Lifetime of Variables

The lifetime of variable, also known as Scope of a variable, is time a variable is accessible during execution and is determined by the context in which it is declared. Let's see what's the scope of various types of variable we have seen so far?

Scope of Instance variables: Instance variables are created for each class. I.e. every object of the class will have its own copies of these variables, which are local to the object. Instance variables exist as long as the object they belong to is in use at runtime.

Scope of Static variables: Static variables belong to Class. These are not specific to any objects of the Class. They are created when the class is loaded at runtime, and exist as long as the class is available at runtime.

Scope of Local variables: Local variables are created for each execution of the method, constructor, or block. After the execution of the method, constructor, or block completes, local variables are no longer accessible.

			package javatutorial;

			/**
			 * Example class explaining the scope of static, instance and local variables
			 * 
			 * @author f5java.com
			 */
			public class ScopeOfVariables {
				
				static String staticVar = "I am a static variable";
				
				String instancevar = "I am an instance variable";
				
				/**
				 * Prints message
				 */
				public void printMehtod(){
					String localVar = "I am a local variable";
					// Local variable is visible in this method and can be accessed
					System.out.println("Print Local Variable" + localVar);
				}
				
				public static void main(String args[]){
					
					// 1. Trying to access local variable
					
			//		System.out.println("Print local variable " + localVar); // Compile time error
					// Reason: Local variable is only visible in the method it is declared in
					
					// 2. Trying to access instance variable
					
			//		System.out.println("Print instance variable " + instanceVar); // Compile time error
					// Reason: instance variable are created per object, in other words instance variable
					// are not visible until you create instances
					ScopeOfVariables varScope = new ScopeOfVariables(); // Instantiating
					System.out.println("Print instance variable " + varScope.instancevar); // Now visible/accessible
					
					// 3. Trying to access static variable
					System.out.println("Printing static variable " + staticVar); // No issues
					// Reason: Static variable doesn't belong to any class and are accessible as long as
					// the class is available at the runtime.
				}

			}