Java Reference
In-Depth Information
Scope
The part of a program in which a particular declaration is valid.
As you've seen, when it comes to declaring static methods, you can put them in
any order whatsoever. The scope of a static method is the entire class in which it
appears. Variables work differently. The simple rule is that the scope of a variable
declaration extends from the point where it is declared to the right curly brace that
encloses it. In other words, find the pair of curly braces that directly encloses the
variable declaration. The scope of the variable is from the point where it is declared
to the closing curly brace.
This scope rule has several implications. Consider first what it means for different
methods. Each method has its own set of curly braces to indicate the statements to be
executed when the method is called. Any variables declared inside a method's curly
braces won't be available outside the method. We refer to such variables as local vari-
ables, and we refer to the process of limiting their scope as localizing variables.
Local Variable
A variable declared inside a method that is accessible only in that method.
Localizing Variables
Declaring variables in the innermost (most local) scope possible.
In general, you will want to declare variables in the most local scope possible. You
might wonder why we would want to localize variables to just one method. Why not
just declare everything in one outer scope? That certainly seems simpler, but there are
some important drawbacks. Localizing variables leads to some duplication (and pos-
sibly confusion) but provides more security. As an analogy, consider the use of refrig-
erators in dormitories. Every dorm room can have its own refrigerator, but if you are
outside a room, you don't know whether it has a refrigerator in it. The contents of the
room are hidden from you.
Java programs use variables to store values just as students use refrigerators to store
beer, ice cream, and other valuables. The last time we were in a dorm we noticed that
most of the individual rooms had refrigerators in them. This seems terribly redundant,
but the reason is obvious. If you want to guarantee the security of something, you put
it where nobody else can get it. You will use local variables in your programs in much
the same way. If each individual method has its own local variables to use, you don't
have to consider possible interference from other parts of the program.
Let's look at a simple example involving two methods:
1 // This program does not compile.
2 public class ScopeExample {
3 public static void main(String[] args) {
 
Search WWH ::




Custom Search