The scope of a parameter of an exception handler that is declared in a catch clause
of a try statement (§14.20) is the entire block associated with the catch.
The scope of a variable declared in the ResourceSpecification of a try-withresources
statement (§14.20.3) is from the declaration rightward over the remainder
of the ResourceSpecification and the entire try block associated with the try-withresources
statement.
The translation of a try-with-resources statement implies the rule above.
Example 6.3-1. Scope of Type Declarations
These rules imply that declarations of class and interface types need not appear before uses
of the types. In the following program, the use of PointList in class Point is valid,
because the scope of the class declaration PointList includes both class Point and class
PointList, as well as any other type declarations in other compilation units of package
points.
package points;
class Point {
int x, y;
PointList list;
Point next;
}
class PointList {
Point first;
}
Example 6.3-2. Scope of Local Variable Declarations
The following program causes a compile-time error because the initialization of local
variable x is within the scope of the declaration of local variable x, but the local variable
x does not yet have a value and cannot be used. The field x has a value of 0 (assigned
when Test1 was initialized) but is a red herring since it is shadowed (§6.4.1) by the local
variable x.
class Test1 {
static int x;
public static void main(String[] args) {
int x = x;
}
}
The following program does compile:
class Test2 {
static int x;
public static void main(String[] args) {
int x = (x=2)*2;