A return statement with no Expression attempts to transfer control to the invoker of the method or constructor that contains it.
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.The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements within the method or constructor whose try blocks contain the return statement, then any finally clauses of
those try statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement.
ok my doubt is when when ever in the method we encounter the return statement ,execution will comes out of method ..why not here it happens
Java has been designed to work in this way when we have return statement in try and finally block. Last line of above mentioned JLS answer your query - Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement. Here, when we add return statement in finally block , we are abrupting normal control flow of try-catch-finally block.
Moreover, if you compile your code with -Xlint option, then an appropriate warning will be generated indicating that you should not call return from a finally clause.
So it is always a bad practice to have a return statement in finally block.
We have two scenarios
1. try block have return statement, finally block have return statement
2. try block have return statement, finally block do not have return statement
Your sample code cater to scenario 1
Let us write a code for Scenario 2
What do you think shall be output here ? Output is 90 (not 100). Reason for getting 90 is because when return i; is executed i has a value 90. After this the finally block is executed where 100 is assigned to i.
After executing finally block , control return back to try block and then try block returns 90, rather than returning 100, because this return statement is not executed again.
if i need to get hello output from the same code what can be done?
You cannot get hello output from same code. you need to modify it a bit
Oracle certified Java 8 Programmer I (1Z0-808), Oracle Java Web Service Developer (1z0-897), Oracle certified Java 7 Programmer, SCJA 1.0, SCJP 5.0, SCWCD 5.0, Oracle SQL Fundamentals I, CIW Certified Ecommerce specialist
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: Return type problem with respect to try and catch block