Google+

46. Scope of Variables






Scope till which the variable can be accessible is defined by blocks in Java Programming. A block beings with an open curly brace and ends by a closing curly brace as shown below:











In Java, two major scopes are those which are defined by a class and method.

class Examplemethod Example

   class ClassName
   {

   }


    public static void MethodName( )
   {

    }

opening and closing curly braces of the class
will define the scope. class scope wont be
explained in this post and will be explained
while explaining the class concept in detail.

opening and closing curly braces of the
 method will define the scope. Method
scope will be explained in this post.

As a general rule, variables declared inside a scope are not visible to code that is defined outside the scope (i.e. outside the opening and closing curly braces).


Program to demonstrate that a variable declared in a method is not visible to the other methods

class VariableScope1
{
public static void main(String args[])
{
int a=5;
AccessVariable( );  // Calling AccessVariable() method, which will in turn will try to print the variable 'a' whose scope is limited to this method only
    }

    public static void AccessVariable( )
    {
System.out.println("a = "+a);     //Trying to print the variable 'a' whose scope is limited to main( ) method only
    }
}

Output of this program:

Error "Cannot find symbol 'a' in System.out.println("a= "+a); statement"

After observing the output its very clear that variable declared in the main( ) method is not visible to the AccessVariable( ) method. i.e. The scope of the variable 'a' is limited to the main( ) method only and cant be accessed outside by any code outside the main( ) method.



Scopes can be nested. When this occurs, the outer scope encloses the inner scope. The objects declared in the outer scope will be visible to code with in the inner scope. How ever the reverse is not true i.e. the objects declared in the inner scope will be not visible outside it.



Program to demonstrate the objects declared in the outer scope will be visible to the code with in the inner scope

class OuterScopeObject
{
     public static void main(String args[])
     {                                                             // Outer scope started
          int a=5;

          if(a>0)        
          {                                                        // Inner scope started
               System.out.println("a="+a);
          }                                                      // Inner scope ended
   
      }                                                                     // Outer scope ended

}

Output of this program:

a=5

The variable 'a' is declared and initialized in the outer loop i.e. main( ) method loop. Where as the value of the variable 'a' got printed in the inner loop i.e. if condition loop. So now its very clear that objects declared in the outer scope will be visible to the code with in the inner scope.



Program to demonstrate the objects declared in the inner scope will not be visible outside it


class InnerScopeObject
{
     public static void main(String args[])
     {                             // Outer scope started

              if(true)
              {                      // Inner scope started
                    int a=5;
              }                     // Inner scope ended

        System.out.println("a="+a);

      }                           // Outer scope ended

 }


Output of this program:

Error "Cannot find the symbol 'a' in the System.out.println("a="+a);"

The variable 'a' is declared and initialized in the inner loop i.e. inside the if condition loop. Where as the program tried to print it in the outside loop i.e. main( ) method loop, but was failed do that. So now its clear that objects declared inside the loop will be not be visible outside it.



Variables cannot be used prior to their declaration

Program to demonstrate that the variables cannot be used prior to their declaration

class UseAndDeclare
{
     public static void main(String args[])
     {
 a=5;   //First use the variable
 int a;  //Second declare the above used variable

       System.out.println("a="+a);

     }
 }

Output of this program:

Error "Cannot find the symbol 'a' in the a=5; "

This means Java is not able to identify  'a' as int type variable, though we have declared the variable 'a'  after using it.



The variable that is declared outside the loop cannot be declared again inside the loop

Program to demonstrate that you cannot declare the same variable inside the loop which is already declared outside the loop.


class SameVariableDeclaration
{
     public static void main(String args[])
     {
 int a;

 if(true)
 {
             int a;
           }

     }
 }

Output of this program:

Error "  'a' is already declared in the main( ) method"

This means that we cant define the same variable inside the loop if it is already declared outside the loop.







Please comment below to feedback or ask questions.

Type conversion concept will be explained in the next post.




2 comments:

Unknown said...

Hi Arun,

I have executed the below code:
class OuterScopeObject
{
public static void main(String args[])
{ // Outer scope started


if(a>0)
{ // Inner scope started
int a=5;
System.out.println("a="+a);

} // Inner scope ended

} // Outer scope ended

}

System is showing an error message, "Cannot find the Symbol."

Can't we execute code with the intitilization and print statement in the same loop? I'm not getting what's happening here.

Could you please clarify this.

Thanks in Advance,
Divya

Arun Motoori said...

@Divya - The variable 'a' is declared inside the if( ) condition statement. As the scope of variable 'a' starts from the starting brace '{' of the if( ) condition statement. The variable 'a' is not visible to the if(a>0) condition statement. Declare the variable int a = 5; outside the if(a>0){ } and your error will get resolved.