I've seen this behavior explained away because it was usually an immutable String in the finally block but I don't understand why an int primitive would behave this way.
"i" is not passed by value as an argument in a method. The method is directly setting the i class variable. This is a obvious because the value of i is changed when printed after the method finishes.
It is also clear that it has been changed prior to the return statement in the try block since the print in the finally block prints first.
public class Test {
static int i = 0;
public static void main(String[] args) {
System.out.println("Try Block returns: " + methodReturningValue());
System.out.println("Value of i after method execution is " + i);
}
static int methodReturningValue()
{
try
{
i = 1;
System.out.println("try block is about to return with an i value of: "+ i);
return i;
}
catch (Exception e)
{
i = 2;
return i;
}
finally
{
i = 3;
System.out.println("Finally block: i has been changed to 3");
}
}
}
Output:
try block is about to return with an i value of: 1
Finally block: i has been changed to 3
Try Block returns: 1
Value of i after method execution is 3