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.
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.
See more on this question at Stackoverflow