Repaso
EspaƱol
Java CoreIntermediateJV-23

What does this print?

static int f() {
    try {
        return 1;
    } finally {
        System.out.println("finally");
    }
}
System.out.println(f());

Options

  1. 1
  2. finally, then 1 (Correct option)
  3. 1, then finally
  4. finally only

Answer

finally, then 1

Why

A finally block runs always, even if the try block executes return. Java first evaluates the return value (1), then runs finally (printing "finally"), then returns 1 to the caller.

So the output is finally on one line and 1 on the next.

Do not put return inside finally: it would replace the original result and even hide exceptions.

Remember

finally always runs, even after return.

Key terms

Practice this question in Repaso