Why does this first if
compile well and the second fail?
if(proceed) {int i;} // This compiles fine.
if(proceed) int i;// This gives an error. (Syntax error on token ")", { expected after this token)
Because the language spec says so:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html
A declaration introduces an entity into a program and includes an identifier (§3.8) that can be used in a name to refer to this entity. A declared entity is one of the following:
...
A local variable, one of the following:
* A local variable declared in a block (§14.4)
* A local variable declared in a for statement (§14.14)
Your first example is declaring i
inside a block (denoted by curly braces). Your second isn't, nor is it a for
statement.
Edited to add: Which just makes commons sense. If it were allowed, it would be useless. It would immediately fall out of scope.
From the Java Language Spec.
Block: { BlockStatementsopt } BlockStatements: BlockStatement BlockStatements BlockStatement BlockStatement: LocalVariableDeclarationStatement ClassDeclaration Statement
and
IfThenStatement: if ( Expression ) Statement
It seems that int i
is a LocalVariableDeclarationStatement
, not a Statement
. So it doesn't work.
This is because it would not be useful code. If you have an if-statement without curly braces ({}), only the first line / statement after the if is executed. So if you only declare a local variable, it cannot be used anywhere else. So declaring it is absolutely superfluous.
if(proceed){
int i= 0;
// variable i can be used here
//...
}
if (proceed) int i; // i can not be used anywhere as it is a local variable
if(proceed) int i;
If we use if
statement without braces it will execute only first line with the if
for the conditional manner. Other lines will execute normally.
This is compilation fail, because local variable declaration happen with conditional manner and compiler assume it is not reachable with the false statement.
If you use a curly braces, then variable declaration and use of local variable within the block and hence compiler assume it is reachable code. Then no compiler errors.
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