Why can't we define a variable immediately after statement statement

public class Foo{    
  public static void main(String []args){  
    int a=10;
    if(a==10)
    int x=20;    
  }
}

When compiling the above code, an error occurs during compilation.

But in the code below, this is normal. Why?

public class Foo{    
  public static void main(String []args){    
    int a=10;    
    if(a==10){    
    int x=20;
    }
  }
}

I do not understand. What exactly is going on in them? As far as I understand, we can write one statement after the if statement without curly braces (a compound statement block).

+4
source share
2 answers

For clarity, the problem is here:

if(a==10)
    int x=20;

... and a mistake error: variable declaration not allowed here.

This is not allowed because there is a specific list of operators that are allowed after if; they are described in detail in JLSยง14.5 :

  • StatementWithoutTrailingSubstatement
  • LabeledStatement
  • IfThenStatement
  • IfThenElseStatement
  • WhileStatement
  • ForStatement

StatementWithoutTrailingSubstatement (the first thing mentioned above) includes:

  • Block
  • EmptyStatement
  • ExpressionStatement
  • AssertStatement
  • SwitchStatement
  • DoStatement
  • BreakStatement
  • ContinueStatement
  • ReturnStatement
  • SynchronizedStatement
  • ThrowStatement
  • TryStatement

, LocalVariableDeclarationStatement . LocalVariableDeclarationStatement Block, , .

? , , . , ? , . ? if? , ? , (, int x = foo();), , (foo();). if ( ), , ? , , , if ...

+13

, , .

. . int x=20 - , if {} . , , undefined , "if" . "x" "if"

public class Foo {

    public static void main(String []args){

        int a=10;

        if(a==10)
            int x=20;

    }
}

, .

, .

0

All Articles