Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange finally behaviour? [duplicate]

Tags:

java

finally

public class Test2 {

    public static void main(String[] args) {
        Test2 obj=new Test2();
        String a=obj.go();

        System.out.print(a);
    }


    public String go() {
        String q="hii";
        try {
            return q;
        }
        finally {
            q="hello";
            System.out.println("finally value of q is "+q);
        }
    }

Why is this printing hii after returning from the function go(), the value has changed to "hello" in the finally block?

the output of the program is

finally value of q is hello
hii
like image 569
Harinder Avatar asked Jun 25 '12 10:06

Harinder


1 Answers

That's because you returned a value that was evaluated from q before you changed the value of q in the finally block. You returned q, which evaluated its value; then you changed q in the finally block, which didn't affect the loaded value; then the return completed, using the evaluated value.

Don't write tricky code like this. If it confuses the guy who wrote it, imagine the problems it will cause the next guy, a few years down the track when you are somewhere else.

like image 77
user207421 Avatar answered Oct 16 '22 16:10

user207421