Scope and Lifetime of Variables in Java

So far, all of the variables used have been declared at the start of the main(). However, Java allows variables to be declared within any block. A block is begun with an opening braces and ended by a closing braces. A block defines a scope.

Thus, each time you start a new block, you start a new block, you are creating a new scope. As a general rule, variables declared inside a scope are not visible(that is ,accessible) to code that is defined outside that scope.

class Scope

{

     public static void main(String arggss[])

     {

           int xx; //known to all code within main

           xx=10;

         if(xx==10)

             {              //start (new scope)

                       int yy=20; //known only to this block

                       //xx and yy both known

                       System.out.println(" xx & yy is :"+xx+" "+yy);

                       xx=yy*2;

           }

       //yy=100;   //error! Y not known here

     //xx is still known here

     System.out.println("xx is"+xx);

     }

}

Scope of Variables

Explanation…

As the comments indicate, the variable xx is declared at the start of main()’s scope and is accessible to all subsequent code within main(). Within the if block, yy is declared, Since a block defines a scope,yy is only visible to other code within its block. This is why outside of its block, the line yy=100; is commented out. If u remove the leading comment symbol, a compile-time error will generate, because yy is not visible outside of its block.

Within the if block, xx can be used because code within a block(that is, a nested scope) has access to variables declared by an enclosing scope.

// Demonstrate lifetime of a variable

class LifeTime

{

       public static void main(String arggss[])

           {

               int xx;

               for(xx=0;xx<3;xx++)

                 {

                     int yy=-1; //yy is initialized each time block is entered

                     System.out.println(" YY value is:"+yy);

                     yy=100;

                   System.out.println(" yy value is now:"+yy);

                 }

           }

}

Scope of Variables

Explanation…

As you can see, yy is always reinitialized to -1 each time the inner for loop(for(xx=0;xx<3;xx++)) is entered. Even though it is subsequently assigned the value 100, this value is lost.

POINT.. Although blocks can be nested, you cannot declare a variable to have name as one in an outer scope.

//This program will not compile

class ScopeErr

{

public static void main(String arggss[])

{

int bar=1;

{ //creates a new scope

int bar=2; //Compile –time error-bar already defined

}

}