Java variable declaration not allowed

Viewed 7017

I've made 2 pieces of code. The first works fine, but the other says the variable declaration not allowed here.

First code(Working)

class Test {
    public static void main(String args[]){
        for(int i=0;i<10;i++) {
            int a[]=new int[10];
        }
    }
}

Second code(Not working)

class Test {
    public static void main(String args[]) {
        for(int i=0;i<10;i++)
            int a[]=new int[10];
    }
}

What is the reason behind it; I think both sections of code are nearly the same.

2 Answers

What the reason behind it i think both the codes are nearly same.

Nearly, but not quite. To understand why the compiler is complaining, it's often a good idea to look at the language specification.

The body of a ForStatement has to be a Statement. A local variable declaration isn't an option for a Statement - it's an option for a BlockStatement.

This is very deliberate. It's deliberately to prevent you from writing pointless code. There's no point in declaring a local variable as the sole statement within a for loop or an if statement etc. It will be out of scope everywhere else, so why declare it?

The case where it's the only statement within a block is still pointless, but it would be harder for the language to prevent you from doing that.

The reason why the second code does not compile is that Java compiler knows for sure that the variable a that you declare as the body of a loop would remain unused. Since there are no curly braces around the declaration, there is absolutely no way to add code that would make any use of your newly declared variable, so Java compiler flags it as an error.

In case of the first program Java compiler can detect that variable is unused, but it cannot be sure that it is an error. It is possible that you started a block of code that you have not finished yet, so the compiler lets you compile the code and run it.

Related