public class Foo{
public static void main(String []args){
int a=10;
if(a==10)
int x=20;
}
}
While compiling above code, an error is thrown at compile.
But, in the below code it is fine. Why?
public class Foo{
public static void main(String []args){
int a=10;
if(a==10){
int x=20;
}
}
}
I don't get it. What exactly is happening in these? As I understand, we can write one statement after an if statement without curly braces (compound statement block).
For clarity, the problem is here:
if(a==10)
int x=20;
...and the error is error: variable declaration not allowed here
.
It's not allowed there because there is a specific list of statements that are allowed following an if
; they're detailed in JLS§14.5:
StatementWithoutTrailingSubstatement
LabeledStatement
IfThenStatement
IfThenElseStatement
WhileStatement
ForStatement
StatementWithoutTrailingSubstatement
(the first thing above) includes:
Block
EmptyStatement
ExpressionStatement
AssertStatement
SwitchStatement
DoStatement
BreakStatement
ContinueStatement
ReturnStatement
SynchronizedStatement
ThrowStatement
TryStatement
Note that LocalVariableDeclarationStatement
does not appear on that list. Whereas LocalVariableDeclarationStatement
is allowed within Block
, so your second example is fine.
Why doesn't it appear on the list? It's always dangerous to speculate why language designers do what they do. But what the heck: Let's say they allowed it. What does it mean? Is it scoped to just the if
's body? That's a bit pointless, isn't it? They it would have no effect other than side-effects from initialization (e.g., int x = foo();
), and in that case you should just write the side-effect-causing thing (foo();
). If it isn't scoped to just the if
's body (it ends up in the containing scope), that's fairly confusing, isn't it? It looks like it wouldn't be declared except if the if
's condition were true...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With