There's nothing like quoting the JLS first thing in the morning.
JLS 6.3. Scope of a Declaration:
The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.
and
JLS 14.2. Blocks:
A block is a sequence of statements, local class declarations, and local variable declaration statements within braces.
What does it mean in your case? The local varialbe w
is declared in the block
{
Stopwatch w = new Stopwatch();
obj = w;
}
("its own initializer" is the first line in the block) and so its scope is the rest of that that block. The reference to it,
System.out.println(w);
is outside of the block and so w
will not be able to resolve to a variable.
What about the local variable obj
then? It was declared in the block
public static void main(String[] args) {
Object obj;
{
Stopwatch w = new Stopwatch();
obj = w;
}
System.out.println(obj);
System.out.println(w);
}
which in this case is a method block. The call
System.out.println(obj);
is inside the block, so obj
can be referenced successfully.