Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we define a variable just after if statement follows [duplicate]

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).

like image 752
Vaibhav Shahapure Avatar asked Dec 11 '22 21:12

Vaibhav Shahapure


1 Answers

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...

like image 159
T.J. Crowder Avatar answered Feb 16 '23 04:02

T.J. Crowder