0

I was going through a couple of questions that are often asked in job interviews (at least in my country - Switzerland), and I was quite unsure about the output of a block of code that is supposed to be tricky. It would be nice to hear what you think the correct answer is.

here it is :

 public class LanguageTest12 {

   public static void main(String... args){
       System.out.println(foo());
   }

   private static int foo() {
      int a = 1, b = 2;
      try {
          return a+b;
      } finally {
          a = 10;
          b = 20;
          return a+b;
     }
   }
 }

I know however that the answer must be one of those three possibilities :

  1. 3
  2. 30
  3. 33

(PS: just in case someone is interested, here are the all the questions : http://se.inf.ethz.ch/courses/2014a_spring/JavaCSharp/exercise_sessions/ExerciseSession5.pdf)

Philippe
  • 700
  • 1
  • 7
  • 17
  • no, I don't want too, I was just looking for a explanation before running it :) – Philippe Nov 19 '14 at 19:03
  • Here, you can see other explanations: http://stackoverflow.com/questions/4559661/java-try-catch-finally-blocks-without-catch – nbro Nov 19 '14 at 19:04
  • 1
    The correct answer is, your IDE and/or FindBugs warns you of a return in a finally block, you fix the code, and you don't write code like that anymore. – David Conrad Nov 19 '14 at 19:21
  • There's a trick question similar to this but with Stringbuffers. you might want to study that too – WillingLearner Nov 20 '14 at 05:23

1 Answers1

4

The finally block is used for code that must always run, whether an error condition (exception) occurred or not.

The code in the finally block is run after the try block completes and, if a caught exception occurred, after the corresponding catch block completes. It should always run, even if an uncaught exception occurred in the try or catch block (Except if you got System.exit(0) in try block, because it will turn down the application before going to the finally block).

So your answer is 2. 30

Machado
  • 14,105
  • 13
  • 56
  • 97
  • 1
    `try { System.exit(0); } finally { System.out.println("almost always"); } ` – Elliott Frisch Nov 19 '14 at 19:16
  • @ElliottFrisch That is extremely pedantic. By definition `System.exit(int)` does not return. It is a given that instructions that come after it will never execute. Assuming that the JVM continues to execute to the end of relevant `try` and `catch` blocks, `finally` blocks will always be run. – Dev Nov 19 '14 at 19:31
  • Thanks ELliott I forgot to take this note. – Machado Nov 19 '14 at 19:31