Java variable declaration not allowed

I have made 2 pieces of code first work fine and other say that variable declaration not allowed here.Please any one can help me.

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 the reason behind it i think both the codes are nearly same.

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow