Missing return statement in java

In Java, missing return statement is a common error which occurs if either we forget to add return statement or use in the wrong scenario.

In this article, we will see the different scenarios whenmissing return statement can occur.

Missing return statement

Here are the few scenarios where we can get Missing return statement error.

Scenario 1

Let’s take an example, where we have a method that returns absolute value of the given positive number. In this example, we computed the absolute value but forgot to return it. When we compile this code, the compiler reports an error. See the example and output.

Output

Error: this method must return a result of type int

Solution

We can solve it by using two ways, either add return statement in the code or set return type as void in the method signature. See the examples below, wherein the first example we have added the return statement. We have also added another method getAbsolute2() and returned void from it in case we don’t want to return anything from the method.

Output:

12
12

Scenario 2

This error can also occur if we have used a return statement in if block. This return statement will execute only when if block executes. Since return statement depends on the if block condition, compiler reports an error. We have to either put return statement in else block or to the end of the method to resolve this.

This method must return a result of type int

Note: A method that has return type in its signature must have return statement.

Solution

If return statement is inside any block like if, for etc. then we need to add an extra return either in else block or in the last line of method body to avoid missing return type error. See the example and output.

Output

0

That’s all about Missing return statement in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *