Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why for loop is not accepting boolean value directly?

Tags:

java

compilation error : The left-hand side of an assignment must be a variable

class A {
    public static void main(String[] args) {

        for(true;true;true) {//compilation error

        }
    }
}

but when I tried this way, there is no compilation error

    class A {
    public static void main(String[] args) {

        for (getBoolean(); true; getBoolean()) {

        }
    }

    public static boolean getBoolean() {
    return true;
    }
}

getBoolean() is returning a boolean value,so for the first case why the for loop is not accepting boolean value directly?

like image 761
Prabhat Avatar asked Mar 02 '15 05:03

Prabhat


2 Answers

From JLS:

BasicForStatement:
    for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement

ForStatementNoShortIf:
    for ( ForInitopt ; Expressionopt ; ForUpdateopt ) StatementNoShortIf

ForInit:
    StatementExpressionList
    LocalVariableDeclaration

ForUpdate:
    StatementExpressionList

StatementExpressionList:
    StatementExpression
    StatementExpressionList , StatementExpression

Then:

 StatementExpression:
    Assignment
    PreIncrementExpression
    PreDecrementExpression
    PostIncrementExpression
    PostDecrementExpression
    MethodInvocation
    ClassInstanceCreationExpression

As you can see Method Invocation is allowed and literal value is not.

like image 53
PM 77-1 Avatar answered Nov 09 '22 15:11

PM 77-1


According to doc

for (initialization; termination;
     increment) {
    statement(s)
}

And intialization and increment must be the expression(assignment) not simple boolean but in java function call is considered as expression so it will evaluate correctly.

like image 4
squiroid Avatar answered Nov 09 '22 14:11

squiroid