3

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
Naman
  • 27,789
  • 26
  • 218
  • 353
B_Ali_Code
  • 65
  • 10
  • 2
    I don’t know why a compile time error would occur, but why are you declaring something in a one statement scope? The declaration of `int u` uses up your single statement. You would not be able to use it, inside, or outside, of the scope. – flmng0 Sep 24 '17 at 10:54
  • 1
    yeah, no use of declaring a single statement but it's a tricky interview question. I'm trying to find the WHY part of every single code. there might be a reason for the compile-time error. thanks for the comment – B_Ali_Code Sep 24 '17 at 10:59
  • 1
    Welcome! Sorry I couldn’t be of more help. Good luck though. – flmng0 Sep 24 '17 at 11:00
  • 1
    Thanks mate! yeah better if we find reason for every single code – B_Ali_Code Sep 24 '17 at 11:01
  • 2
    The same happens with `if`: https://stackoverflow.com/questions/9206618 – Jorn Vernee Sep 24 '17 at 11:32

2 Answers2

3

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
2

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).

Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56