CHAPTER 14: Blocks and Statements Previous
Previous
Java Language
Java Language
Index
Index
Next
Next

14.3 Local Variable Declaration Statements

14.3.1 Local Variable Declarators and Types , 14.3.2 Scope of Local Variable Declarations , 14.3.3 Hiding of Names by Local Variables , 14.3.4 Execution of Local Variable Declarations

A local variable declaration statement declares one or more local variable names.


LocalVariableDeclarationStatement:

	LocalVariableDeclaration ;

LocalVariableDeclaration:

	Type VariableDeclarators

The following are repeated from S8.3 to make the presentation here clearer:


VariableDeclarators:

	VariableDeclarator

	VariableDeclarators , VariableDeclarator

VariableDeclarator:

	VariableDeclaratorId

	VariableDeclaratorId = VariableInitializer

VariableDeclaratorId:

	Identifier

	VariableDeclaratorId [ ]

VariableInitializer:

	Expression

	ArrayInitializer

Every local variable declaration statement is immediately contained by a block. Local variable declaration statements may be intermixed freely with other kinds of statements in the block.

A local variable declaration can also appear in the header of a for statement (S14.12). In this case it is executed in the same manner as if it were part of a local variable declaration statement.


14.3.1 Local Variable Declarators and Types

Each declarator in a local variable declaration declares one local variable, whose name is the Identifier that appears in the declarator.

The type of the variable is denoted by the Type that appears at the start of the local variable declaration, followed by any bracket pairs that follow the Identifier in the declarator. Thus, the local variable declaration:

int a, b[], c[][];

is equivalent to the series of declarations:


int a;
int[] b;
int[][] c;

Brackets are allowed in declarators as a nod to the tradition of C and C++. The general rule, however, also means that the local variable declaration:

float[][] f[][], g[][][], h[];													// Yechh!

is equivalent to the series of declarations:


float[][][][] f;
float[][][][][] g;
float[][][] h;

We do not recommend such "mixed notation" for array declarations.


14.3.2 Scope of Local Variable Declarations

The scope of a local variable declared in a block is the rest of the block, including its own initializer. The name of the local variable parameter may not be redeclared as a local variable or exception parameter within its scope, or a compile-time error occurs; that is, hiding the name of a local variable is not permitted.

A local variable cannot be referred to using a qualified name (S6.6), only a simple name.

The example:


class Test {
	static int x;
	public static void main(String[] args) {
		int x = x;
	}
}

causes a compile-time error because the initialization of x is within the scope of the declaration of x as a local variable, and the local x does not yet have a value and cannot be used.

The following program does compile:


class Test {
	static int x;
	public static void main(String[] args) {
		int x = (x=2)*2;
		System.out.println(x);
	}
}

because the local variable x is definitely assigned (Chapter 16) before it is used. It prints:

4

Here is another example:


class Test {
	public static void main(String[] args) {
		System.out.print("2+1=");
		int two = 2, three = two + 1;
		System.out.println(three);
	}
}

which compiles correctly and produces the output:

2+1=3

The initializer for three can correctly refer to the variable two declared in an earlier declarator, and the method invocation in the next line can correctly refer to the variable three declared earlier in the block.

The scope of a local variable declared in a for statement is the rest of the for statement, including its own initializer.

If a declaration of an identifier as a local variable appears within the scope of a parameter or local variable of the same name, a compile-time error occurs. Thus the following example does not compile:


class Test {
	public static void main(String[] args) {
		int i;
		for (int i = 0; i < 10; i++)
			System.out.println(i);
	}
}

This restriction helps to detect some otherwise very obscure bugs. (A similar restriction on hiding of members by local variables was judged impractical, because the addition of a member in a superclass could cause subclasses to have to rename local variables.)

On the other hand, local variables with the same name may be declared in two separate blocks or for statements neither of which contains the other. Thus:


class Test {
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++)
			System.out.print(i + " ");
		for (int i = 10; i > 0; i--)
			System.out.print(i + " ");
		System.out.println();
	}
}

compiles without error and, when executed, produces the output:

0 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1


14.3.3 Hiding of Names by Local Variables

If a name declared as a local variable is already declared as a field or type name, then that outer declaration is hidden throughout the scope of the local variable. The field or type name can almost always (S6.8) still be accessed using an appropriately qualified name. For example, the keyword this can be used to access a hidden field x , using the form this.x . Indeed, this idiom typically appears in constructors (S8.6):


class Pair {
	Object first, second;
	public Pair(Object first, Object second) {
		this.first = first;
		this.second = second;
	}
}

In this example, the constructor takes parameters having the same names as the fields to be initialized. This is simpler than having to invent different names for the parameters and is not too confusing in this stylized context. In general, however, it is considered poor style to have local variables with the same names as fields.


14.3.4 Execution of Local Variable Declarations

A local variable declaration statement is an executable statement. Every time it is executed, the declarators are processed in order from left to right. If a declarator has an initialization expression, the expression is evaluated and its value is assigned to the variable. If a declarator does not have an initialization expression, then a Java compiler must prove, using exactly the algorithm given in Chapter 16, that every reference to the variable is necessarily preceded by execution of an assignment to the variable. If this is not the case, then a compile-time error occurs.

Each initialization (except the first) is executed only if the evaluation of the preceding initialization expression completes normally. Execution of the local variable declaration completes normally only if evaluation of the last initialization expression completes normally; if the local variable declaration contains no initialization expressions, then executing it always completes normally.

Top© 1996 Sun Microsystems, Inc. All rights reserved.