Execution Order of finally and return, finallyreturn order
I saw a question in the cvte 2015 interview question:
5. What is the output of the following program?
Public class FinallyTest1 {
Static char label;
Public static void main (String [] args ){
System. out. println (test1 ());
System. out. println (label );
}
Public static char test1 (){
Try {
System. out. println ('A ');
Return label = 'a ';
}
Finally {
System. out. println ('B ');
Label = 'B ';
}
}
}
Amount... No. The answer is:
A
B
A
B
I did not know much about this before, so I ran it myself.
package k;public class k { static char label; public static void main(String[] args) { System.out.println(test1()); System.out.println('3'); System.out.println(label); } public static char test1() { try { System.out.println('A'); System.out.println('1'); return label = 'A'; } finally { System.out.println('B'); System.out.println('2'); label = 'B'; } }}
Result output:
A
1
B
2
A
3
B
It can be seen that the return statement has been executed before the finally statement is executed, but the finally statement is not directly returned, but the result is returned after the finally statement is executed. The variable value changed in finally does not affect the results returned by try.