Variable gets garbage collected immediately after catch block

Viewed 873

I can see this curious behaviour from the garbage collector

public class A {
    public static void main(String[] args) {

        String foo;
        try {
            foo = "bar";

            int yoo = 5; //1
        } catch (Exception e) {
        }

        int foobar = 3;//2 
    }
}

if I go to debug and put a breakpoint on //1 foo is not null and its value is "bar" but in breakpoint //2 foo is null, this can be difficult to understand while you are debug. My question is if there is any specification that says that this is a legal behaviour from the garbage collector

With this small variation it doesn't get Garbage collected:

public class A {
    public static void main(String[] args) {

        String foo;
        try {
            foo = "bar";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        int foobar = 3;
    }
}

Why?

4 Answers
Related