Java Reference
In-Depth Information
{
// Reference to n here is OK too
// Reference to m here is still an error
int m = 2; // Declare and define m
// Reference to m and n are OK here - they both exist
} // m dies at this point
// Reference to m here is now an error
// Reference to n is still OK though
} // n dies at this point so you can't refer to it in following statements
A variable does not exist before its declaration; you can refer to it only after it has been declared. It con-
tinues to exist until the end of the block in which it is defined, and that includes any blocks nested within the
block containing its declaration. The variable n is created as the first statement in the outer block. It contin-
ues to exist within the inner block too. The variable m exists only within the inner block because that's where
its declaration appears. After the brace at the end of the inner block, m no longer exists so you can't refer to
it. The variable n is still around, though, and it survives until the closing brace of the outer block.
So, the rule that determines the accessibility of local variables is simple. Local variables are accessible
only from the point in the program where they are declared to the end of the block that contains the declar-
ation. At the end of the block in which they are declared, they cease to exist. I can demonstrate this with an
example.
TRY IT OUT: Scoping
Here's a version of the main() method that demonstrates how variable scope works:
public class Scope {
public static void main(String[] args) {
int outer = 1;
// Exists throughout
the method
{
// You cannot refer to a variable before its declaration
// Uncomment the following statement for an error
// System.out.println("inner = " + inner);
int inner = 2;
System.out.println("inner = " + inner);
// Now it is OK
System.out.println("outer = " + outer);
// and outer is
still here
// All variables defined in the enclosing outer block still
exist,
Search WWH ::




Custom Search