Search code examples
javacompilationreturnunreachable-statement

should a return statement be the last instruction within a code block?


I really need help understanding what does an unreachable statement actually means in Java. I have the following below and when I try to compile I get an unreachable statement error. I have looked at some of the similar questions about unreachable statements here on Stackoverflow, but none answer my question. I want to know based on how the return statements work why this version does not compile.

public int refundBalance()
{
    return balance;
    balance = 0;
}

I am asking this because similar questions in here don't give me an answer. I am guessing that return should be the last statement within a block of code, but I am not knowledgeable enough in Java to be certain about my conclusion. So, any clarification would be greatly appreciated.


Solution

  • When the return statement is executed, what do you expect to happen next!? Control returns to the calling program and the statement following return can never be executed.

    It looks like you really want to implement this function, which apparently refunds the current balance as follows:

    public int refundBalance() {
        int result = balance;
        balance = 0;
        return result;
    }