0

Please check the below code and explain the out behavior:

    class ExceptionTest2 {
        int x = 5;

        public int TestMethod2() {
            try {
                x = x + 2;
                System.out.println("x value in try: " + x);
                return x;
            } catch (Exception e) {

            } finally {
                x = x + 3;
                System.out.println("x value in finally: " + x);
            }
            return x;
        }

    }

    public class ExceptionProg2 {

        public static void main(String[] args) {
            ExceptionTest2 test2 = new ExceptionTest2();
            int res = test2.TestMethod2();
            System.out.println("Res : " + res); // it should return 10 but returning 7.
        }

    }

Here it is returning 7 instead of 10.

Here is the actual o/p:

x value in try: 7
x value in finally: 10
Res : 7

Why it is behaving like this, when the x value gets changed in finally block and 'x' is not a local variable.

Please clarify my doubt.

Sandy
  • 972
  • 5
  • 15
  • 28

1 Answers1

1

When X is return from try block, the value is stored on the stack frame for that method and after that the finally block is executed.

Kick
  • 4,823
  • 3
  • 22
  • 29
  • But that value which is stored in stack frame getting changed right !!! – Sandy Feb 04 '14 at 07:31
  • 3
    @Sandy: Wrong. The instance member is getting changed, but the value on the stack is a *copy* of the value in the instance member, not a reference to it. *Exactly* like: `x = 5; int y = x; x = x + 3; System.out.println(y);` outputs `5`, not `8`. – T.J. Crowder Feb 04 '14 at 07:32
  • No the value of the stack will not change,but if you return the value from finally block then yes the value will change.. – Kick Feb 04 '14 at 07:33
  • @Crowder: Thanks. Now its pretty clear to me. For premitive return statement holds the value right! But for Object reference it holds the reference? for example returning StringBuilder from try and append something in finally block. Please explain. – Sandy Feb 04 '14 at 08:03