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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With