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.
Table of Contents
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Main { static int getAbsolute(int val) { Math.abs(val); } public static void main(String[] args){ int a = -12; int result = getAbsolute(a); System.out.println(result); } } |
Output
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Main { static int getAbsolute(int val) { return Math.abs(val); // adding return statement } // set void static void getAbsolute2(int val) { System.out.println(Math.abs(val)); } public static void main(String[] args){ int a = -12; int result = getAbsolute(a); System.out.println(result); getAbsolute2(a); } } |
Output:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Main { static int getAbsolute(int val) { int abs_val = Math.abs(val); if(val>0) return abs_val; } public static void main(String[] args){ int a = -12; int result = getAbsolute(a); System.out.println(result); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Main { static int getAbsolute(int val) { int abs_val = Math.abs(val); if(val>0) return abs_val; return 0; } public static void main(String[] args){ int a = -12; int result = getAbsolute(a); System.out.println(result); } } |
Output
That’s all about Missing return statement in java.