Execution Order of finally and return, finallyreturn order

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.