Tricky Output: finally Overrides and Initialization Order

Difficulty: Advanced

Question

What does a method print or return when finally has its own return? What is the order of static blocks, instance blocks and constructors in inheritance, and what happens when a constructor calls an overridden method?

Answer

These two puzzles are the ones that separate people who have written Java from people who understand how the language executes. Let me take them in turn and give you the mental model for each.

Puzzle one is finally versus return. The rule is that a finally block always runs when control leaves the try block, including through return. But what value does the caller receive? Consider a method with try { return 1; } finally { return 2; }. The return in finally wins and the method returns 2, discarding the earlier return. In the same way, an exception thrown in try can be swallowed by a return in finally, which is why compilers and linters warn about it.

Now a different case: int x = 1; try { return x; } finally { x = 99; }. The method returns 1. When the try executes return x, the value of x is evaluated and saved as the pending return value. Then finally runs and changes the local variable, but the saved value is untouched. So the caller gets 1. For a mutable object reference, though, the saved value is the reference, so changes to the object made in finally are visible to the caller. A useful memory hook: return evaluates first, finally runs second, and only a return or throw inside finally can replace the outcome.

Puzzle two is the order of initialization. When you create an object of a subclass for the first time, the sequence is precise. First, class loading and static initialization happen from the top of the hierarchy down: the parent's static blocks and static fields run in textual order, then the child's static blocks. This happens once per class. Then, for each new object, the constructor chain works top-down: the parent's instance initializer blocks and field initializers run, then the parent constructor body, then the child's instance initializers and field initializers, then the child's constructor body. Note that a constructor implicitly starts with super(), and instance initializers run right after the super call returns and before the rest of the constructor body.

The nastiest twist: what if the parent constructor calls a method that the child overrides? Polymorphism still applies during construction, so the child's version runs, but the child's fields have not been initialized yet because the child's initializers run only after the parent constructor finishes. The child method therefore sees default values: 0 for int, null for objects. In the example below, the child's show prints v=0 even though the field is declared as int v = 5. This is a well-known reason for the guideline: never call overridable methods from a constructor.

A supporting fact: static initialization is triggered lazily. Merely declaring a variable of the class does not initialize it; creating an instance, calling a static method, or accessing a non-constant static field does. Compile-time constants (static final primitives or Strings initialized with constants) are inlined and do not trigger initialization.

In the interview, walk through it as a numbered sequence, and mention the design lesson at the end. That combination turns a trick question into a chance to show engineering judgment.

Code examples

finally and return

public class FinallyReturn {
    static int f() {
        try {
            return 1;
        } finally {
            return 2;
        }
    }

    static int g() {
        int x = 1;
        try {
            return x;
        } finally {
            x = 99;
        }
    }

    public static void main(String[] args) {
        System.out.println(f());
        System.out.println(g());
    }
}

f returns 2 because the return in finally replaces the earlier one (compilers warn about this). g returns 1 because the return value was already saved before finally changed x.

Initialization order with an overridden method

class Parent {
    static { System.out.println("Parent static"); }
    { System.out.println("Parent instance"); }

    Parent() {
        System.out.println("Parent ctor");
        show();
    }

    void show() {
        System.out.println("Parent show");
    }
}

class Child extends Parent {
    static { System.out.println("Child static"); }
    int v = 5;
    { System.out.println("Child instance"); }

    Child() {
        System.out.println("Child ctor");
    }

    @Override
    void show() {
        System.out.println("Child show v=" + v);
    }
}

public class InitOrder {
    public static void main(String[] args) {
        new Child();
    }
}

Static blocks run once, parent first. Then the parent instance block and constructor run. The overridden show is called before the child's field v is initialized, so it sees 0.

Key points

Common follow-up questions

Interview tips

Concepts covered

finally, Initialization Order, Static Block, Constructor, Polymorphism

More Core Java & Collections questions