We know that the return statement is used in a certain method. One is used to return the execution result of the function, and the other is used in functions with a return value of void type. It is just a return statement (return ;). At this time, it is used to end the execution of the method, that is, the statement after this return will not be executed. Of course, in this case, there can no longer be any other statement after the return statement.
I encountered some questions using return statement in try-catch-finally statement
Code 1:
static int intc(){int x =0;try{x=1;return x;} finally {x = 3; }} Code 2: Add a return statement to the finally statement of the code above
static int intc(){int x =0;try{x=1;return x;} finally {x = 3;return x;}}Code Three:
static int intc(){int x =0;try{x=1;return x;} finally {x = 3;return 0;}} So what are the execution results of these three methods?
Code 1: Return 1;
Code 2: Return 3;
Code 3: Return 0;
What's the principle?
The reason is that when a java virtual machine executes a method with a return value, it will create an area in the local variable list to store the return value of the method. When executing the return statement, it will read the value from this area for return.
In code 1, assign 1 to variable x in try, and then copy the value of variable x to the area where the return value is stored. Finally, the return value area stores 1, and one is returned when the return statement is executed.
In code 2, 1 is also assigned to the variable x, and then the value of x is copied to the area where the return value is stored. At this time, the value of the area where the return value is 1, and then jumps to the finally statement. At this time, 3 is assigned to the local variable x, and then copy the value of x to the area where the return value is stored, and finally executes the return statement. The value in the returned area read is 3.
In Code Three, the statements executed in try are the same. After jumping to the finally statement, 3 is assigned to the local variable, then 0 is assigned to the area where the return value is stored, and finally the return statement is executed. The value in the returned area read is 0, so 0 is returned.