Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return within a for loop [duplicate]

Tags:

java

for-loop

jls

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; }
}
like image 691
assylias Avatar asked Jan 15 '23 09:01

assylias


2 Answers

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

like image 184
vishal_aim Avatar answered Jan 22 '23 00:01

vishal_aim


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.

like image 21
AlexWien Avatar answered Jan 22 '23 00:01

AlexWien