Local Variables

  1. Local variables are variables defined inside a method:

    Example:
          public class Dictionary
          {
    	 ...
    	 public void enterWord(String w, String def)
    	 {
    	    int i;
    	    String x;
    
    	    ....
    	 }
          }
    
          public class myProgram
          {
    	 public static void main(String argv[])
    	 {
    	    Dictionary d;
    	    int i, j, k;
    	    String s;
    
    	    ...
    	 }
          }
    
    

  2. Purpose of Local Variables:

  3. Lifetime of a local variable:

  4. Scope of a local variable:


    Scoping                   Scoping                   Scoping                   Scoping

  5. The concept of scoping

  6. Denoting the boundary of a scope:

    Example:
         .....
          { (Outer scope)
            ....
            ....
            { (Begin of inner scope)
              (Inner scope)
              ....
              ....
            } (End of inner scope)
            ....
            ....
          }
    

  7. An example of scoping:

    Example: inner scope inherits variables from outer scope
          public class myClass
          {
             public void myMethod(....)
             {
                int x;
                ... // int x is accessible after its definition
                ...
                while (....)
                { Start of new scope...
                   ...
                   ... // int x is ALSO accessible in new scope
                   ...
                   ...
                }
             }
          }
    

  8. Another example of scoping:

    Example: variables ceases to exists at end of its scope
          public class myClass
          {
             public void myMethod(....)
             {
    	    ....
                { Start of new scope...
                   int x;
                   ... // x is accessible in inner scope
                   ...
                   ...
                }
    
    	    // x is NOT accessible after the end of inner scope
    
    	 }
          }
    

    DEMO: click here

  9. An inner scope:

    Example: C or C++ only, is NOT allowed in Java....
       void main()
       {
          int x;
          ... // the name "x" in this part refers to int x
          ...
    
          {
             ... // the name "x" in this part still refers to int x
             ...
             double a;   // <-- adds a new variable to scope
             double x;   // <-- shadows variable in outer scope
             ...
             ... // the name "x" in this part now refers to double x
             ...
             ...
          }
       }
    

    DEMO: click here