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:
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:
In the case of the third method, there is a condition expression and it is not a constant expression because
iis not final. So the for statement can complete normally and the method can too as a consequence.QED.