0

In the following code snippet, the value of j changed to 20 in the finally block is ignored and the original value of 10 is returned.

public class Test{

    public static void main(String args[]){
        int i=testMethod(10);
        System.out.println(i);
    }

    public static int testMethod(int j){
        try{
            return j;
        }finally{
            j=20;
        }
    }
}
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
  • If you want to return j as 20 then put the return statement after the finally block instead of in try block. – Top.Deck Jul 14 '17 at 18:11

1 Answers1

1

The finally is executed after the entire try block completes. That means, in this case, j has already been read and is about to be returned. j will not be re-read after it is assigned in the finally block, so the assignment has no apparent effect.

arshajii
  • 127,459
  • 24
  • 238
  • 287