+ 5

Why is the output 2?

I just answered the following challenge in Java and my answer (which is 1) is wrong and the correct answer is 2. Please help me to understand. Here is the challenge: what is the output of this code? public static int getValue(){ try { return 1; } finally { return 2; } } public static void main(String[] args){ System.out.print(getValue()); }

6th Nov 2017, 2:34 PM
Vahid Shirbisheh
Vahid Shirbisheh - avatar
6 Answers
+ 6
I think the finally block must execute before the function can return anything so 2 gets returned
6th Nov 2017, 2:55 PM
David Akhihiero
David Akhihiero - avatar
+ 6
Thanks guys. I tried it with different combinations of statements including the version proposed by @LukArToDo. It seems if we have a return statement in finally block it ignores the other return statements. But if we have no return statement in finally block other return statements will work.
6th Nov 2017, 3:14 PM
Vahid Shirbisheh
Vahid Shirbisheh - avatar
+ 5
finally block will override the try block exception if finally block has an exception. it means try block exception will disappear in clear. so it will return 2 only.
6th Nov 2017, 3:04 PM
anu
anu - avatar
+ 5
@LukAr there will be cases , we need to handle few things in finally block, so when their comes an exception in finally and try block, it will only return finally block exception statement also further statement in finally block won't get executed.
6th Nov 2017, 3:12 PM
anu
anu - avatar
+ 5
Sometimes we need to execute something in try block, and after that return value with finally block (to be sure that value will be returned no matter what happens in try block, for example exception)
6th Nov 2017, 3:18 PM
LukArToDo
LukArToDo - avatar
+ 4
The output is always 2, as we are returning 2 from the finally block. Remember the finally always execute after try or try-catch block whether there is a exception or not. So when the finally block runs it will override the return value of others blocks. Writing return statements in finally block is not required, in fact you should not write it. For example, try next: public static int getValue(){ try { System.out.println ("Hello" ) ; return 1; } finally { return 2; } } public static void main(String[] args){ System.out.print(getValue()); } Output will be: Hello 2
6th Nov 2017, 3:08 PM
LukArToDo
LukArToDo - avatar