Friday, May 24, 2013

Scope and LifeTime of The Variable

SCOPE OF VARIABLE:-

Scope of the variable is defined by the block. If a particular variable is can be used by only a method or loop or whole program is called its scope i.e. Scope of that variable.




There are two types of variable:-

         1) GLOBAL:- if the variable is used by whole program then that variable is called global variable and its scope called global scope of that variable.

         2) LOCAL:- if the variable is used by particular block of the code or loop or method then it called local variable and its scope is called local scope of that variable.
Following source code will clear the above idea:-
                                     
class ScopeOfVar
{
       public static void main(String args[])
       {
              int a;                       // known to all code within main
              a = 10;
              if(a == 10)
              {                               // start new scope
                     int b = 20;       // known only to this block
                                  
 //a and b both known here.
        System.out.println("a and b: " + a + " " + b);
        a = b * 2;
   }

// b = 40;             // Error! variable b not known here
// variable a is still known here.
System.out.println("a is " + b);
}
}

Description:-
In above program variable a is known to whole program. If it used anywhere in the program will not show the error. Hence in this program, variable a is called Global variable. Variable b is declared in if() loop, hence if we used variable b outside the loop it will show the error that undefined variable : b. Hence in this program, variable b is called Local variable.

LIFETIME OF VARIABLE:-

LifeTime of the variable is depends upon, till what the variable is executed. Take a look at following program:-

class LifeTimeOfVar
{
       public static void main(String args[])
       {
              int a;
              for(a = 0; a < 3; a++)
              {
                     System.out.println(a);
              }
       }
}

Description:-

In above program, variable a will execute only 3 times i.e. limited number of times. Hence, variable a has limited life. So, in above case, LifeTime of variable a is 3.

0 comments:

Post a Comment

    Translate

    Protected by Copyscape