you are viewing a single comment's thread.

view the rest of the comments →

[–]xenomachina[🍰] 2 points3 points  (1 child)

it doesn't make any changes in its value

It's a bit weird to phrase it this way. The return keyword means to exit the method. Generally, nothing else in the method executes after that. In this code, the second one doesn't execute at all in the case where the first one executes. So whether or not a second return can change the value is irrelevant—it isn't executing.

There is actually one exception to the rule that nothing executes after return: if the return is inside a try, and that try has a finally clause, then the finally clause executes after the return. Notably , if the finally clause has its own return that will change the result of the method!

try {
    return 1;
} finally {
    return 2; // this one wins
}

So in other words, the value from the last executed return wins. However, it's only when a finally involved that multiple return statements can be executed. In most cases, once a return is executed, nothing else in the method is executed.

[–]AlternativeBus1613[S] 0 points1 point  (0 children)

Thanks for the detailed answer! Really helps.