public class SomeClass{
    public static void main (String[] args){
        if(true) int a = 0;// this is being considered as an error 
        if(true){
            int b =0;
        }//this works pretty fine
    }
}//end class
In the above class first if statement is showing an compilation error
Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    Syntax error on token "int", delete this token
    a cannot be resolved to a variable
However second if statement works fine. I just cannot figure it out myself. I know it is of no use declaring a variable in a single statement if. How those two statements are different can some one please explain me. Excuse me if the question is really simple.
To define the scope of int a you need curly braces. That's why you get compiler error for 
if(true) int a = 0;
while this works :
if(true){
    int b =0;
}
See JLS §14.9 for if statements,
IfThenStatement:
    if ( Expression ) Statement
While in if(true) int a = 0;, int a = 0 is LocalVariableDeclarationStatement
It is specified in the java language specification. The IfThenStatement is specified as
if ( Expression ) Statement
int a = 0; is not a statement, but a LocalVariableDeclarationStatement (which is not a subtype of Statement). But a Block is a Statement and a LocalVariableDeclarationStatement is legal content of a block.
 if (true) int a = 0;
           ^--------^    LocalVariableDeclarationStatement, not allowed here!
 if (true) {int a = 0;}
           ^----------^  Statement (Block), allowed.
Reference
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