Lets analyze what your first code example would mean for the language design
if(condition)
int a = 10;
else
int b = 20;
Either it means that depending on the condition we have defined a
or b
. As we don't know which branch was taken, how do we use either a
or b
after the if-statement? We can't (and if we could that would probably result in strange bugs).
So as language designers we decide that a
and b
are not visible outside their respective branches to avoid these weird bugs. But as a block-less branch can only have a single statement, we have declared a
(or b
) only to be immediately unreachable/unusable again, so doing that makes no sense. Therefor we decide that a variable declaration is only allowed with a block. A block can have multiple statements, so variables declared in that block can be used by those other statements.
The designers of Java probably applied similar reasoning, so they decided to only allow declaration in a block. This is done through the definition of if
(JLS 14.9):
IfThenStatement:
if ( Expression ) Statement
IfThenElseStatement:
if ( Expression ) StatementNoShortIf else Statement
IfThenElseStatementNoShortIf:
if ( Expression ) StatementNoShortIf else StatementNoShortIf
Statement
(JLS 14.5)
Statement:
StatementWithoutTrailingSubstatement
...
StatementNoShortIf:
StatementWithoutTrailingSubstatement
...
StatementWithoutTrailingSubstatement:
Block
...
Block
(JLS 14.2):
Block:
{ [BlockStatements] }
BlockStatements:
BlockStatement {BlockStatement}
BlockStatement:
LocalVariableDeclarationStatement
ClassDeclaration
Statement
And LocalVariableDeclarationStatement
(JLS 14.4), which repeats that it can only occur within a immediately enclosing block:
Every local variable declaration statement is immediately contained by a block. Local variable declaration statements may be intermixed freely with other kinds of statements in the block.