Question

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; }
}
Was it helpful?

Solution 3

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.

OTHER TIPS

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 (§14.1).

see method body

and Normal and Abrupt Completion of Statements

Such a method must have a return statement that is garuanteed to be executed, which is not the case in v3.
There are cases where with human intelligence you know that it is garuanteed that return is called, but the compiler can not know it.

Java makes sure that if a method has a return type then something must be returned in any case.If the return statement is inside a conditional statement, it may or may not be executed. Hence you will have to put a return statement outside the for loop for your code to compile. in the second case there is no condition so no problem

The function having some return type must assure return statement .Return statement in any conditional block does not guarantee the value to be return. So you may get the warning.

but in case 3 the condition is false in the beginning so you get the error.

try some ex:

int abc1(){
    if(x>5)    // warning because return is possible but not assured.
    return x;
}

int abc2(){
x=0        
if(x>0)    // error because return is  not possible
return x;
}

int abc3(){        
if(x>0)    // no error no warning because return is  assured. 
return x;
else
return 1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top