Lifetime of variables in Java

  1. Variables in a program get "created" and get "destroyed"

  2. Creating a variable means:

  3. Destroying a variable means:


  4. We have seen 4 kinds of variables:

    Each type of variables has its own lifetime.


  5. Lifetime of Instance variables:

  6. Lifetime of Static variables:

  7. Lifetime of Local variables:

    Example: local variable
          public class myClass
          {
             public void myMethod(...)
    	 {
    	    ...
    	    ...
    	    int x;  // <-- Local variable   
    	    ...
    	    ...
    	 }
          }
    
    • x is created when int x; is executed.
    • x is destroyed when "myMethod" returns

    Example: local variable
          public class myClass
          {
             public void myMethod(...)
    	 {
    	    ...
    	    if ( ... )
    	    {  
    	       ....
    	       ....
    	       int x;  // <-- Local variable   
    	       ....
    	       ....
    	    }
    	 }
          }
    
    • x is created when int x; is executed.
    • x is destroyed when "if" block exits

  8. Lifetime of Parameter variables:

    Example: parameter variable
          public class myClass
          {
             public void myMethod(int x)    
    	 {
    	    ...
    	    ...
    	 }
          }
    

    Conclusion: A parameter variable has the same lifetime as a local variable defined at the beginning of a method .