Java Reference
In-Depth Information
These levels of scope are ordered so that variables that are defined in a higher level can be accessed from
lower‐level locations. To give the simplest example, instance variables (highest level) can be accessed
by all methods inside the class. Method arguments (a parameter variable) can only be accessed by that
method, but not by other methods. This is exactly why the previous example doesn't work.
Figure 4-3 graphically illustrates the scope of an instance variable ( instanceVar ), a parameter vari-
able ( paramVar ), and a local variable ( localVarA ).
figure 4-3  
As the example in Figure 4-3 shows, the instance variable ( instanceVar ) is accessible by each
method in the class. Parameter variables are accessible only within their methods, and can thus re‐
use the same name throughout different method definitions. Finally, locally declared variables (such
as localVarA ) are accessible only within their method, meaning that method makeB will not be able
to access localVarA .
Note that parameter variables are accessible only within their method or loop. What do I mean by
their loop? I will leave the main explanation regarding loops for the next chapter, but the following
example provides a sneak preview:
class ScopeTest {
void doTheLoop() {
String[] names = new String[]{"Alice", "Bob", "Mia", "Marcus"};
for (int i = 0; i < names.length; i++) {
System.out.println("Name number "+i+" equals: "+names[i]);
}
System.out.println("The value of i is now: "+i); // Will not work
}
}
Again, you have one class definition, with one method, taking no arguments this time. Inside the
method, you have one local variable ( names ) followed by a so‐called for loop. Don't concern your-
self with the specifics of this construct for now, just understand that this code basically says, “For an
integer i going from 0 but not including the number of names. That is, for i equal to 0, 1, 2, and 3,
do whatever's inside this block.” What is important to know, however, is that the variable i is only
available within the for block, which is why the last println statement in the previous code snippet
will throw an error in Eclipse, as i is no longer accessible at this point. Another point to note is that
the names variable is also accessible from within the loop block. Again, this illustrates the basic rule
Search WWH ::




Custom Search