A finally problem

As follows, what is the printed result after running the program?

public class FinallyTest {
    public static void main(String[] args){
        int result = m();
        System.out.println(result);
    }

    public static int m(a){
        int i = 100;
        try {
            return i;
        }finally{ i++; }}}Copy the code

As we all know, the Finally key in Java is usually used with a try. After a program enters a try block, the contents of the Finally block must be executed, whether the program aborts because of an exception or otherwise returns a termination. Using finally, you can maintain the internal state of an object and clean up non-memory resources.

For beginners, I =100, then when I return I, execute the finally block. I becomes 101, then return. Sout is 101, and the result is 100. Why is that? The teacher clearly didn’t understand how it worked, so I went looking for answers.

/* Decompilation */
public static int m(a){
	int i = 100;
	int j = i;
	i++;
	return j;
	Exception exception;
	exception;
	i++;
	throw exception;
}
Copy the code

This is the result of decompilation. I don’t really understand it.

After reading some articles, I found that this is a heap and stack problem.

In simple terms, when a try block returns I, the value 100 of I is cached ina local variable. Finally is reassigned, but the value returned is not affected by the finally block. That’s the problem with base variables on the stack.

If you look at the following code block, StringBuffer is a modifiable string, the cache returns the address value, and the output is exactly the same as the finally rule.

public class Test {
        public static void main(String[] args) {
                StringBuffer buffer = testFinally2();
                System.out.println(buffer);

        }
        private static StringBuffer testFinally2(a){
                StringBuffer s = new StringBuffer("Hello");
                try {
                        return s;
                } catch (Exception e) {
                        return s;
                } finally {
                        s.append("World"); }}}Copy the code

The above is simple personal understanding, if there are mistakes, welcome to correct and supplement!

Resources: blog.csdn.net/maijia0754/…