1

If finally block executes before return statement present in side try block, then why return list is not printing null instead printing [DEV].

public class Sub {
 List list = new ArrayList();

  public List check(){
    try {
        list.add("DEV");
        return list;
    }finally{
        list = null;    
                System.out.println("Inside finally ["+list+"]");
    }
  }

  public static void main(String[] args) {
    Sub sup = new Sub();

    System.out.println(sup.check());
    System.out.println(sup.list);
  }
}

O/P:

  • Inside finally [null]
  • [DEV]
  • null
ManishS
  • 627
  • 2
  • 11
  • 21

2 Answers2

0

The value object referred by list is updated on the stack before finally statement is executed. This is how it goes

  • List item return list; in try block updates the object referred by list on stack.
  • On the other hand, even if finally block is executed after try block, assignment list = null; is done but the value is not updated on the stack. It does not change the returned value.
  • Statement System.out.println(sup.check()); prints DEV because it is the value returned from try block i.e. which was updated on the stack.
  • Here System.out.println(sup.list); you are directly referring to list variable which was set to null using list = null; in finally block which does not update the value on stack.
Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
-1

Finally doesnt execute before return, it executes after it, when the return value of the method is already set.

I dont't know why people marked this down. I maintain that it is the simple correct answer. If we disregard the possibility of exceptions, an equivalent implementation of the check() method is:

public List check() {

    // try block part        
    list.add("DEV");
    List ret_val = list;

    // finally block part
    list = null;    
    System.out.println("Inside finally ["+list+"]");

    // and then actually exit the method
    return ret_val;
}

That is, return in the presence of a finally block does not mean “exit immediately”, but “set the pending return value, and exit when the finally block is done”.

njlarsson
  • 2,128
  • 1
  • 18
  • 27