“Missing return statement” within if / for / while in Java

0 votes

I have this method which returns a String value, but my problem is whenever I am executing this code the compiler is returning the error missing return statement. What am I missing here?

public String myMethod()
{
    if(condition)
    {
       return xyz;
    }
}
Sep 26, 2018 in Java by v.liyyah
• 1,300 points
3,958 views

1 answer to this question.

0 votes

Putting a return statement in any of the iterative statements may or may not return value. Problem with your code is that you need to provide an else condition for the cases where if condition isn't true. This is why you are getting the error.

But in case you write if/else block, each with a return statement in it then compiler then it will not force you. Thus, you need to write your code as follows:

if(condition)
{
 return;
}
else
{
 return;
}
answered Sep 26, 2018 by code.reaper12
• 3,470 points

Related Questions In Java

0 votes
1 answer

Performance difference of if/else vs switch statement in Java

The thing you are worried about is ...READ MORE

answered Jul 26, 2018 in Java by geek.erkami
• 2,680 points
1,104 views
+1 vote
2 answers

How to generate random integers within specific range in Java?

You can achieve that concisely in Java: Random ...READ MORE

answered Jul 25, 2018 in Java by samarth295
• 2,200 points
204 views
0 votes
3 answers

Check if a String is numeric in Java

Java 8 Lambda Expression is used: String someString ...READ MORE

answered Sep 3, 2018 in Java by Daisy
• 8,110 points
1,860 views
0 votes
1 answer

I am learning looping statements. Can you tell me how 'for-each' works in Java?

While programming we often write code that ...READ MORE

answered Apr 17, 2018 in Java by Rishabh
• 3,580 points
152 views
0 votes
1 answer

Are arrays equivalent to objects in Java ?

Yes; the Java Language Specification writes: In the Java ...READ MORE

answered May 10, 2018 in Java by Rishabh
• 3,580 points
193 views
0 votes
1 answer

What are optional parameters in Java

Using three dots: public void move(Object... x) { ...READ MORE

answered Apr 27, 2018 in Java by developer_1
• 3,300 points
184 views
0 votes
1 answer

How to split Strings by space in Java ?

You can use split() method. str = "Hello ...READ MORE

answered May 16, 2018 in Java by sharth
• 3,370 points
204 views
0 votes
3 answers

How to clear the console in Java?

import java.io.IOException; public class chkClearScreen {     public static void ...READ MORE

answered Aug 26 in Java by ItsJustRaja
17,090 views
0 votes
1 answer

Need for finalize() in Java

finalize() is a method called by the ...READ MORE

answered May 8, 2018 in Java by code.reaper12
• 3,470 points
141 views
0 votes
1 answer

Overloaded method for null in Java

The method invoked here will be the ...READ MORE

answered May 23, 2018 in Java by code.reaper12
• 3,470 points
170 views