Why doesn't for loop take boolean directly?

compilation error: the left part of the job must be a variable

class A { public static void main(String[] args) { for(true;true;true) {//compilation error } } } 

but when i tried this way, compilation error

  class A { public static void main(String[] args) { for (getBoolean(); true; getBoolean()) { } } public static boolean getBoolean() { return true; } } 

getBoolean () returns a boolean, so in the first case, why doesn't the for loop take a boolean directly?

+7
java
source share
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 allowed and literal value not.

+14
source share

According to the document

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

Both intialization and increment should be an expression (assignment) not just a logical one, but in a java function the call is considered as an expression, so it will evaluate correctly.

+4
source share

All Articles