Why can't we use declarative statement after while loop without curly braces?

Viewed 468

Without using curly braces why can't we use declarative statement after while loop?

With Curley braces it compails :

while(true){
    int u =89;
}

Without curly braces, a compile-time error occurs:

while(true)
    int u =89; // compile time error
2 Answers

The syntactical reason is that the element after the while statement is statement, which includes all the executable statements, and specifically blocks, but does not include declarations.

The design reason is that it wouldn't make the least bit of sense. The scope of the declared variable would terminate at the concluding semicolon, so the declared variable would be of no possible use in the succeeding program text.

I just had a look into the grammar of Java found on oracle.com: Chapter 18. Syntax. (I hope it is the correct version which applies to the question.)

Statement:
    Block
    ;
    Identifier : Statement
    StatementExpression ;
    if ParExpression Statement [else Statement] 
    assert Expression [: Expression] ;
    switch ParExpression { SwitchBlockStatementGroups } 
    while ParExpression Statement
    do Statement while ParExpression ;
    for ( ForControl ) Statement
    break [Identifier] ;
    continue [Identifier] ;
    return [Expression] ;
    throw Expression ;
    synchronized ParExpression Block
    try Block (Catches | [Catches] Finally)
    try ResourceSpecification Block [Catches] [Finally]

Thus, you can see while is followed by ParExpression (expression in parentheses) and Statement.

For

while(true){
    int u =89;
}

the Statement after of whiles body expands to Block which in turn may expand to a LocalVariableDeclarationStatement.

For

while(true)
    int u =89; // compile time error

the Statement of whiles body cannot expand to LocalVariableDeclarationStatement as there is no Block.

Thus, the 2nd simply isn't part of the Java language (based on its grammar).

Related