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.