[PRL] Java and shadowing local variable declarations

Richard Cobbe cobbe at ccs.neu.edu
Mon Jun 5 16:22:53 EDT 2006


How does local-variable shadowing in Java 1.4 work?  (For the purposes
of this conversation, a "local variable" is a variable that is declared
inside a block, as distinct from a field in a class or interface, a
method parameter, a constructor parameter, or an exception-handler
parameter.)

Because one can nest blocks arbitrarily deeply in Java, I had assumed
that local variables declared in an inner block would shadow local
variables declared in an outer block, and indeed the text in section
6.3.1 of the Java Language Specification, 2nd edition (JLS2) seems to
support this.  (Keep in mind that method bodies and constructor bodies
are considered blocks.)  However, the following class fails to compile:

    public class Foo {
        public static void main(String[] args) {
            boolean x = true;
            {
                int x = 42;
                System.out.println(x);
            }
        }
    }

    Foo.java:5: x is already defined in main(java.lang.String[])
                int x = 42;
                    ^

The relevant language appears to be in section 14.4.2 of JLS2:

    The name of a local variable _v_ may not be redeclared as a local
    variable of the directly enclosing method, constructor or
    initializer block with the scope of _v_, or a compile-time error
    occurs.

(Italics theirs.)  

What does this sentence mean?

Other than that the person who wrote that particularly tortured piece of
English should be taken out behind the barn and shot, that is.

Richard

(Just to make this clear: I do in fact need to know the answer to this
question; I'm not just venting about the bad writing in the JLS.)



More information about the PRL mailing list