Java Reference
In-Depth Information
happens to have the same name as a variable declared in some other method, they are two
different variables that just happen to have the same name. Thus, all the variables we have
seen so far are either local variables or instance variables. There is only one more kind of vari-
able in Java, which is known as a static variable. Static variables will be discussed in Chapter 5.
Local Variable
A variable declared within a method definition is called a local variable . If two methods
each have a local variable of the same name, they are two different variables that just hap-
pen to have the same name.
Global Variables
Thus far, we have discussed two kinds of variables: instance variables, whose meaning is
confined to an object of a class, and local variables, whose meaning is confined to a method
definition. Some other programming languages have another kind of variable called a global
variable , whose meaning is confined only to the program. Java does not have these global
variables.
Blocks
The terms block and compound statement mean the same thing, namely, a set of
Java statements enclosed in braces, {} . However, programmers tend to use the two
terms in different contexts. When you declare a variable within a compound state-
ment, the compound statement is usually called a block.
block
compound
statement
Blocks
A block is another name for a compound statement—that is, a list of statements enclosed
in braces. However, programmers tend to use the two terms in different contexts. When
you declare a variable within a compound statement, the compound statement is usually
called a block. The variables declared in a block are local to the block, so these variables dis-
appear when the execution of the block is completed. However, even though the variables
are local to the block, their names cannot be used for anything else within the same method
definition.
If you declare a variable within a block, that variable is local to the block. This means
that when the block ends, all variables declared within the block disappear. In many pro-
gramming languages, you can even use that variable's name to name some other variable
outside the block. However, in Java, you cannot have two variables with the same name
inside a single method definition. Local variables within blocks can sometimes create
Search WWH ::




Custom Search