0

For below program i am getting output as below.
Output:
In try
In finally
3

Why it is not returning 7 instead of 3?

public class MyFirstJavaProgram {
   public static void main(String []args) {
      int c = 10;
      c=get(c);
      System.out.println(c);
   }
   public static int get(int c){
       try{
       c=3;
       System.out.println("In try");
      return c;
       }
       catch(Exception e){
           c=5;
           System.out.println("In catch");
           return c;
       }
       finally{
           c=7;
           System.out.println("In finally");
       }
   }
}
  • finnally bloc is not always executed, for more infos looks at this repsonse https://stackoverflow.com/questions/65035/does-a-finally-block-always-get-executed-in-java – DEV Aug 14 '21 at 12:42
  • 1
    Does this answer your question? [Why does changing the returned variable in a finally block not change the return value?](https://stackoverflow.com/questions/16030858/why-does-changing-the-returned-variable-in-a-finally-block-not-change-the-return) – İsmail Y. Aug 14 '21 at 12:45
  • 1
    You're not "returning a variable", you are returning a value. The return value has been determined to be 3 by evaluating the expression `c`. Subsequent changes to `c` have nothing to do with the prior result. – user16632363 Aug 14 '21 at 13:36

0 Answers0