Unreachable Statement in Java With Examples

An unreachable statement in Java is a compile-time error. This error occurs when there is a statement in your code that will not be executed even once. This error points out a logical flaw in the flow of your code.

Such an error can arise from an infinite loop or placing code after a return or a break statement among several other causes.

Let’s look at a few examples of unreachable statements.

1. Unreachable While loop

If the condition of a while loop is such that it is never true, then the code inside the loop will never run. This makes the code inside the while loop un-reachable.

The IDE points out the error while writing the code. That’s quite ‘intelliJ’ent.

Upon running we get :


2. Code after an infinite loop

A piece of code just after an infinite loop will never be executed. In fact, the entire code after the infinite loop will never be executed. This should motivate you to pay attention while writing the terminating condition of a loop.

3. Code after a break or continue statement

Break statement lets us break out of a loop. Continue statement lets us skip the current iteration and move to the next iteration Placing code after either of the two makes the statement unreachable.

statement after continue

How to fix an Unreachable Statement error?

There is no particular way to fix such an error. It all depends on how good you are as a programmer. The problem is in the flow of your code.

Flowcharts are essential for understanding the flow of any code. You can try drawing the flowchart for the problem you are trying to address. Then you can match your code with the flowchart or write the code from scratch from this new understanding of the problem.

Another question this type of error could pose is whether you even need the statements that are unreachable? Maybe you don’t really need the statements, in that case, you can just go ahead and delete them.

If you are still not able to figure it out, you can always comment on this post and we’ll help you figure it out. That’s what we are here for 🙂

By admin

Leave a Reply

%d bloggers like this: