This is because of the way the return statement function and the way it interact with a try with finally statement.
The Section §14.17 of the JLS describe the return statement.
A return statement with an Expression attempts to transfer control to the invoker of the method that contains it; the value of the Expression becomes the value of the method invocation. More precisely, execution of such a return statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the return statement completes abruptly for that reason. If evaluation of the Expression completes normally, producing a value V, then the return statement completes abruptly, the reason being a return with value V.
The last sentence indicates that if the expression of the return statement is evaluated normally, then the return statement completes abrutptly. In your example, the try
block terminates abrutply because of the return
statement and the reason being a return
value 10 (i
is evaluated to value 10).
Since in your example the return
is in a try with finally block, Section §14.20.2 of the JLS tells us what happens next:
- If execution of the try block completes abruptly for any other reason
R, then the finally block is executed, and then there is a choice:
- If the finally block completes normally, then the try statement completes abruptly for reason R.
- If the finally block completes abruptly for reason S, then the try statement completes bruptly for reason S (and reason R is discarded).
So, since the try
block terminated abruptly because of the return statement being evaluated to value 10, and because the finally block completes normally, then the method returns 10.