Return to for loop

Possible duplicate:
Why is this happening?

The 3 methods below do exactly the same and obviously return true.

However, the first two compilations, but the third is not executed ("missing return statement").

What part of the language specification dictates this behavior?

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; } } 
+4
source share
5 answers

The compiler throws an error in accordance with JLS 8.4.7 , because it determines that the method can finish normally:

If the method returns a return value type, then a compile-time error occurs if the body of the method can complete normally.

To determine if a method can function normally, the compiler must determine if the for loop can complete normally, as defined in JLS 14.21

The base statement can complete normally if at least one of the following is true:

  • A for statement is available, a condition expression exists, and the condition expression is not a constant expression with a value of true.
  • There is a valid break statement that completes the for statement.

In the case of the third method, a condition expression exists, and it is not a constant expression, since i not final. Thus, the for statement can complete normally, and the method can also be the last.

QED

+2
source

If the method returns a return type, then a compile-time error occurs if the body of the method can function normally (Β§14.1).

cm

and normal and abrupt completion of statements

+4
source

Such a method must have a return statement that is executed to execute, which does not apply to v3.
There are times when, with the help of human intelligence, you know that it is called the return call, but the compiler cannot know this.

+3
source

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

0
source

A function that has some type of return value must provide a return statement. The return statement in any conditional block does not guarantee the return of a value. Therefore, you may receive a warning.

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

try an example:

 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; } 
0
source

All Articles