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.
It is specified in the java language specification. The
IfThenStatementis specified asint a = 0;is not a statement, but aLocalVariableDeclarationStatement(which is not a subtype ofStatement). But aBlockis aStatementand aLocalVariableDeclarationStatementis legal content of a block.Reference