N Kaushik

Solved- Java missing return statement error

September 30, 2021

Java missing return statement error:

There is a good chance that you will face missing return statement error if you are new to Programming. This is a Java compile time error and it appears if you are missing any return stament from a method.

In this post, I will show you how to fix this error and a couple of examples with this error.

Example 1:

Let’s take a look at the below program:

public class Main {

    static int getValue(){
        System.out.println("Inside getValue");
    }

    public static void main(String[] args) {
        getValue();
    }
}

If you write this program, your IDE will show you the missing return statement error. On IntelliJ-Idea, it looks as like below:

Java missing return statement error

This is because,

  • getValue method is defined to return an int value, but we are not returning anything.

To solve this,

  • either make getValue to return void:
static void getValue(){
    System.out.println("Inside getValue");
}
  • or, return an integer.
static int getValue(){
    System.out.println("Inside getValue");
    return -1;
}

If we are defining a method that it is returning something, we have to return a value of the same type.

Example 2:

Now, let’s take a look at the below program:

public class Main {

    static String getValue(int v) {
        if (v == 0)
            return "Zero";
    }

    public static void main(String[] args) {
        getValue(1);
    }
}

I have changed the getValue method to take an integer as the parameter and the return value to String.

This method checks if the value of v, i.e. the passed parameter is equal to 0 or not. If yes, it returns the string Zero.

But, it still throws the same error.

This is because, we have a return statement for the if condition. But we don’t have any return statement if the if condition fails. So, we have to add one default return statement.

static String getValue(int v) {
    if (v == 0)
        return "Zero";
    return "";
}

But, if you have a else statement at the end, you don’t have to add a return statement.

static String getValue(int v) {
    if (v == 0)
        return "Zero";
    else if (v == 1)
        return "One";
    else
        return "Other";
}

else block will run always if it fail for if and else if.

Conclusion:

No matter what, always check for all possible scenarios. If your method is working for some specific values, it might not work for some other values. Make sure to add the return statement for all possible scenarios.


Subscribe to my Newsletter

© 2021, nkaushik