Java

Scope of a Variable (OCAJP 1.1)

Scope of  a variable actually mean the life of a variable or the duration for which the variable will be available around.

There are various types of variables.

  • static variable

 

  • instance variable

 

  • local variable

 

  • block variable

 

  • init block variable

 

  • constructor variable
All these variable have their own scopes, some server longer some serve shorter in the runtime  of a Java class.
 
Let us consider the following example.
 
class MyClass
{
	static int count=0;

	int i ;

	{
		i=6;
		int y=10;
	}

	MyClass()
	{
		i=i+1;
		int k=7;
	}

	public void m1()
	{
		int z=9;

		for (int j=0;j<10 ;j++ )
		{
			z=z+j;
		}

	}
}

Now in the given example we have got many types of variables.

  • count is a static variable.

 

  • i is an instance variable

 

  • y is an init block variable - a type of local variable.

 

  • k is a constructor variable- a type of local variable.

 

  • z is a local variable.

 

  • j is a block variable.
Now all the scopes have some specified living time.
Following is an image depicting the same.
 
There are some common mistakes programmers make while working with variables.
1. Using instance variable in static area(majorly in main())
Let say for example we have a class Pen
class Pen 
{
 int inkLevel=100;
 public static void main(String[] args) 
 {
  inkLevel--;
 }
}

Now inkLevel is a instance variable and will get loaded when the instance of the class will be loaded, but main() is a static method it get loaded when class is loaded in JVM and it always happens before instance loading. Hence inkLevel is not available for use when main() is loaded and hence it gives the following error.

2. Attempting a local variable from a nested method.
Simple rule for local variable is that it will be only available in the method in which it is declared and at not other place.
Let see.

class MethodScope
{
 public static void main(String[] args) 
 {
  MethodScope s=new MethodScope();
  s.m1();
 }

 public void m1()
 {
  int i=10;
  m2();
 }

 public void m2()
 {
  i++;

 }

 
}

Variable i is only available in method m1() so any attempt to use it outside will result in an error.

3. Using block variable after block is executed.

Variable declared in for loop will be only available till the execution on loop. Not after that.

class BlockScope 
{
 public static void main(String[] args) 
 {
  for (int i=0;i>10 ;i++ )
  {
   System.out.println(""+i);
  }
  i++;
 }
}

Here variable i is block variable and is available only till loop is executing not after that.

Related Posts

Table Of Contents

;