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.
Our website is not responsible for the information contained by this article. Webworldarticles.com is a free articles resource thus practically any visitor can submit an article. However if you notice any copyrighted material, please contact us and we will remove the article(s) in discussion right away.
This article was sent to us by:
Gabriela C. Perez at
12292007
1. Java EE Architecture
All articles in this directory are property of their respective authors. Additionally, read our Privacy Policy
© 2010 WebWorldarticles.com - All Rights Reserved. Partners: Gunblade Saga