+1 vote
2 views
in Java by (1.2k 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;
    }
}

1 Answer

0 votes
by (10.4k 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;
    }

...