質問

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.

役に立ちましたか?

解決

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;
}

他のヒント

Yes, a return statement should be the last statement in a block of code. If it's not, then any code below it won't ever be reached, because the return statement transfers control to the method that called the current method (or to a finally block first, if it exists). There is no point to code in a block after a return statement, so it's disallowed.

Not only does the return statement dictate what the current function returns, it also causes the function to terminate. Therefor, the statement after return is truly unreachable under any circumstance, and should not exist.

In order for this to work you would have to set another variable to balance, then set balance to 0, then return the other variable.

​The return statement causes the method to exit. So any statement after the return statement in the same block of code will never be executed. That is why you are getting this error.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top