Tuesday 27 May 2014

Why the return value is 0 instead of 100?

public class FinallyReturnVariableAlter
{
   public static void main(String[] args)
  {
     System.out.println(test());
  }

  public static int test()
 {
    int i=0;
    try
   {
      return i;
   }
   finally
  {
    i+=100;
  }
  }
}

 Answer By Lokesh Gupta :
  • Every function call in java leads to creation of extra memory space created where return value is stored for reference after function execution completes and execution return to caller function back.
  • At that time, that special memory address where return value is stored, if referenced back as return value of function.
  • Here, trick is, the memory slot store the value of returned value, not its reference. So, once any return statement is encountered its value is copied in memory slot. That’s why if you change the value of “i” in finally, return value does not change because its already copied to memory slot.
  • We any other return statement is encountered (e.g. in finally block), its value will be overwritten again. So, it you want to return 100, use return statement in finally also.;

No comments:

Post a Comment