Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
5 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;
    }

by (100 points)
public int searchInsert(int[] nums, int target) {
        for(int i=0;i<nums.length;i++){
            if(nums[i] <= target)
                if(nums[i] == target)
                    return i;
                else
                    return i+1;
            else
                return i;
        }
    }

In this case, added return statement for each if and else, I still get the same error. Can you please help here!
+1 vote
by (32.3k points)
edited by

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.

Want to learn Java from scratch! Here's the right video for you on Java:

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;

}

Related questions

0 votes
2 answers
asked Sep 12, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 18, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...