Variable Scope

written by: Gabriela C. Perez; article published: year 2007, month 12;


In: Root » Computers and technology » JAVA » Variable Scope

Dutch French Spanish Portuguese Italian German Japanese Chinese Korean Russian Arabic Bookmark and Share this Article

The scope of a variable is the area in which a variable belongs, specified by the area in which it is declared. The following example code contains two declared variables, one inside a code block and one outside of that code block (imagine that the code is entered into a method, like main for example).

int outside = 10;
     
   {
   int inside = 5;
   // outside is valid inside this code block
   inside = outside;
   }
   
   outside = 5;
   // inside cannot be accessed here

The variable inside cannot be accessed anywhere outside the code block in which it was declared because it is out of the variable's scope. The variable inside simply does not exist outside of the code block. Therefore, this is true of all code blocks, like the ones belonging to while and for loops and if and else statements and methods.

For example, look at this for loop:

for(int counter=0; counter<5; counter++)
   {
   System.out.println("counter = " + counter);
   }

The variable counter is declared in the scope of the for loop code block; it only exists inside this code block and cannot be accessed further on in the code outside of the code block. If you want to access the counter variable later in the code, implement your code like this:

int counter;
     
   for(counter=0; counter<5; counter++)
   {
   System.out.println("counter = " + counter);
   }
   
   System.out.println("counter final value = " + counter);

Here we simply declare the variable counter before the for loop and then use it with the for loop in the same way but this time we do not declare it at the first stage of the for loop. Later, outside of the for loop code block, we can still access the variable counter because it has been declared within the scope of this area.

A variable declared inside a method is known as a local variable to that method and does not exist outside of the method.

Disclaimer

1) E-articles is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringement, please read the terms of service and contact us to investigate the problem.
2) E-articles is not responsible for inaccuracies, falsehoods, or any other types of misinformation this article may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here.

link to this article