10.12.2012 Views

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

BLOCKS AND STATEMENTS Scope of Local Variable Declarations 14.4.2<br />

including any further declarators to the right in the local variable declaration statement.<br />

<strong>The</strong> name of a local variable v may not be redeclared as a local variable of the<br />

directly enclosing method, constructor or initializer block within the scope of v,or<br />

a compile-time error occurs. <strong>The</strong> name of a local variable v may not be redeclared<br />

as an exception parameter of a catch clause in a try statement of the directly<br />

enclosing method, constructor or initializer block within the scope of v, or a compile-time<br />

error occurs. However, a local variable of a method or initializer block<br />

may be shadowed (§6.3.1) anywhere inside a class declaration nested within the<br />

scope of the local variable.<br />

A local variable cannot be referred to using a qualified name (§6.6), only a<br />

simple name.<br />

<strong>The</strong> example:<br />

class Test {<br />

static int x;<br />

public static void main(String[] args) {<br />

int x = x;<br />

}<br />

}<br />

causes a compile-time error because the initialization of x is within the scope of<br />

the declaration of x as a local variable, and the local x does not yet have a value<br />

and cannot be used.<br />

<strong>The</strong> following program does compile:<br />

class Test {<br />

static int x;<br />

public static void main(String[] args) {<br />

int x = (x=2)*2;<br />

System.out.println(x);<br />

}<br />

}<br />

because the local variable x is definitely assigned (§16) before it is used. It prints:<br />

4<br />

Here is another example:<br />

class Test {<br />

public static void main(String[] args) {<br />

System.out.print("2+1=");<br />

int two = 2, three = two + 1;<br />

System.out.println(three);<br />

}<br />

}<br />

which compiles correctly and produces the output:<br />

2+1=3<br />

DRAFT<br />

365

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!