Variable Scope

So far in this chapter we have used variables as soon as they have been declared, without really encountering problems with the scope of the variables. 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. So far, we have only declared variables inside methods. In the next chapter, we will start declaring class variables declared within the class code block only and not local to any method, meaning you will be able to access and manipulate these variables from any method. We will see this notably in Chapter 4.



Java 1.4 Game Programming
Java 1.4 Game Programming (Wordware Game and Graphics Library)
ISBN: 1556229631
EAN: 2147483647
Year: 2003
Pages: 237

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net