Interview Q&A / Java

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What does a Java method return when both try and finally contain a return?

SHORT ANSWER

The finally block runs before the method actually returns, and a return inside finally overrides the earlier one, so the finally value wins. If finally only changes a variable, a primitive value already chosen for return is not affected.

Explain it simply

You hand a cheque to the clerk (the return value is noted down), but before you leave the counter the clerk must do the closing formalities (finally). If the formalities hand you a different cheque, that one replaces the first. If they only scribble on your copy of the original, the noted amount does not change.

Example

java
static int a() {
    try { return 1; }
    finally { return 2; }          // overrides
}
static int b() {
    int x = 1;
    try { return x; }              // value 1 is saved for returning
    finally { x = 5; }             // changes the variable, not the saved value
}
System.out.println(a());   // prints: 2
System.out.println(b());   // prints: 1

What to say in the interview

"The return expression in try is evaluated first and its result is stored, then finally runs, then the method completes. A return in finally replaces the stored value and even swallows an exception that was in flight, which is why it is considered bad practice and compilers warn about it. For an object return, finally can still modify the object's contents because the reference is the same."

Common mistakes

  • Returning from finally to be tidy. It silently discards exceptions.

#java#exceptions#finally

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.