+2 votes
2 views
in Java by (1.3k points)

I have been using java for awhile now, there is a question bothering me. Whenever I use the return statement for a method in if(), while() or for() loop, I get an error " Missing return statement". I have already given a return statement but it is inside a statement or loop. Then why am I getting an error. Here, is a code as an example.

public int example()
{
    if(condition)
    {
       return value;
    }
}

2 Answers

+1 vote
by (13.2k points)

You are getting the error because a function must always return a value. Imagine what will happen if you execute example() and it does not go into “ if ” condition, what will your function return? Compiler needs to know what to return in every situation, hence it gives you the error. You can correct this by either putting an “ else “ condition with a return statement or by putting return statement towards the end of the function.

 public int example()
    {
         int result = -1;
         if(condition)
          {

              result = x;
         }

        return result;
    }

+1 vote
by (25.3k points)

That is illegal syntax. Returning a variable is not an optional thing. You should always keep in mind this thing and return a variable of the type you specify in your method.

Imagine what happens if you execute myMethod() and it doesn't go into if(condition) what would your function return? The compiler needs to know what to return in every possible execution of your function

In order to solve your problem, do this:


 

public int example()

{

    int result = null;

    if(condition)

    {

       result = x;

    }

    return result;

}

...