Possible Duplicate:
Why does this get error?
The 3 methods below do exactly the same thing and obviously return true.
However, the first two compile but the third one does not ("missing return statement").
What part of the language specification dictates that behaviour?
boolean returnTrue_1() { // returns true
return true;
}
boolean returnTrue_2() { // returns true
for (int i = 0; ; i++) { return true; }
}
boolean returnTrue_3() { // "missing return statement"
for (int i = 0; i < 1; i++) { return true; }
}
The compiler gives an error in compliance with JLS 8.4.7, because it determines that the method can complete normally:
If a method is declared to have a return type, then a compile-time error occurs if the body of the method can complete normally.
To determine if the method can complete normally, the compiler needs to determine whether the for loop can complete normally, which is defined in JLS 14.21:
A basic for statement can complete normally iff at least one of the following is true:
- The for statement is reachable, there is a condition expression, and the condition expression is not a constant expression with value true.
- There is a reachable break statement that exits the for statement.
In the case of the third method, there is a condition expression and it is not a constant expression because i
is not final. So the for statement can complete normally and the method can too as a consequence.
QED.