Error missing return statement java

I wrote code to get a number from the user, then check whether the number is prime. My code is: import java.util.*; public class hanoo { public static void main(String args[]) { Scanner...

I wrote code to get a number from the user, then check whether the number is prime.

My code is:

import java.util.*;
public class hanoo {
    public static void main(String args[]) {
      Scanner input = new Scanner(System.in);
      System.out.println("please enter an integer number");
      int number = input.nextInt();
      System.out.println(num(number));
    } 

    public static String num(int number) {
      for (int i = 2; i < number; i++) {
        if (number % i != 0)
          return "it is prime";
        else
          return "it is not prime";  
      }         
   }   
}

It gives me a missing return statement error!

q1.java:17: error: missing return statement
   }
   ^
1 error

----jGRASP wedge2: exit code for process is 1.

What should I do ?

Adi Inbar's user avatar

Adi Inbar

11.8k13 gold badges54 silver badges69 bronze badges

asked Nov 19, 2013 at 13:38

user2957980's user avatar

1

Your function currently does not necessarily return anything. This is the case when number is smaller than or equal to 2. You should add a return statement outside of your for loop, so that the function will always return something.

Side note: The logic to decide whether a number is a prime or not is wrong. If the current function was valid, it would return it is prime if the number was odd and it is not prime if the number was even.

answered Nov 19, 2013 at 13:40

Patrick Kostjens's user avatar

Patrick KostjensPatrick Kostjens

5,0156 gold badges29 silver badges46 bronze badges

1

While the other answers havd correctly pointed out why you are getting the error, I feel obliged to point out that your code (and other answers here) will not correctly indicate whether the number is prime, or not. Try this instead:

public static String num(int number){

   for (int i = 2 ; i<number ;i++){
     if(number %i == 0) {
          // it has an exact factor.
          return "it is not prime" ;
     }
   }
   return "it is prime" ;
}

ddmps's user avatar

ddmps

4,3201 gold badge19 silver badges34 bronze badges

answered Nov 19, 2013 at 13:43

rolfl's user avatar

rolflrolfl

17.4k7 gold badges41 silver badges76 bronze badges

1

If number variable is less or equal then for loop will not run. So return statement in for statement will not work. To fix your compilation error you should add return statement after for block. Your code will look something like this:

public static String num(int number){

   for (int i = 2 ; i<number ;i++){
      if (number%i!=0)
         return "it is prime";
      else
         return "it is not prime";
   }
   return "some message";
}

answered Nov 19, 2013 at 13:44

Nikoloz's user avatar

NikolozNikoloz

4431 gold badge3 silver badges10 bronze badges

the reason your for loop not execute by condition failed, what is the return value??.so it is a error. try this..

public static String num(int number){
       String result = "";
       for (int i = 2 ; i<number ;i++){
         if(number%i!=0)
         result = "it is prime" ;
         else
         result =  "it is not prime" ;
      }
      return result;
 }

answered Nov 19, 2013 at 13:40

subash's user avatar

subashsubash

3,0762 gold badges17 silver badges22 bronze badges

0

You should return the else outside the for loop

public static String num(int number){

   for (int i = 2 ; i<number ;i++){
     if(number%i!=0)
         return "it is prime" ;

   }
   return "it is not prime" ; 
}

If the condition inside the if statement is met, then it will return «is prime» and the «not prime» will not be returned. If the if condition is never met in the loop, the «not prime» will be returned.

answered Nov 19, 2013 at 13:40

Paul Samsotha's user avatar

Paul SamsothaPaul Samsotha

202k35 gold badges478 silver badges710 bronze badges

4

In java, a method which has defined return type can not end normally with out returning. You must return value from the method with out any implicit/explicit condition. A method like following is ok:

public int getInt()
{
   if(true)return 1;
   else return 0;
}

But a method which is returning as following:

public int getInt()
{
       if(true)return 1;
       else if(false)return 0;
}

will ask for return statement because after the second end condition, it can’t evaluate the conditions other than the run time. For your case how ever, The problem is with the for loop. Whither it can go inside the for loop or not can’t be evaluated at the compile time. So your program must pass the compile time ensuring that even if your for loop wasn’t executed, it does return.

public static String num(int number){

   for (int i = 2 ; i<number ;i++){
     if(number%i == 0)  // <---- i have changed the condition
        return "it is not prime" ;


   return "it is prime";

}

answered Nov 19, 2013 at 13:51

Sage's user avatar

SageSage

15.2k3 gold badges32 silver badges37 bronze badges

You do not have to iterate up until the tested number n. It is enough to iterate only to sqrt(n). That is enough as both of the dividers cannot be greater than sqrt(n), because (a + sqrt(n)) * (b + sqrt(n)) > n for any a,b > 0.

A fiddle code to demonstrate that is at http://dew.apidesign.org/dew/#7545568

answered Nov 19, 2013 at 21:52

Jaroslav Tulach's user avatar

The missing return statement is one of the most occurred errors in the Java program. The beginners usually face the missing return statement error. It is a compile-time error, it means that the error is raised when we compile program. The name of the error states the root cause of the error is that the return statement is missing in the program.

The Java missing return statement error mainly occurs due to human mistakes. It occurs when we use the return type before the method name and doesn’t use the return statement. In Java, there can be two possible cases:

  1. Method missing the return statement.
  2. Missing return statement error within if / while / for.

Java missing return statement

Let’s understand both the cases one by one.

Method missing the return statement

In this case, we will get the missing return statement when the method uses the return type but doesn’t return any value. Let’s take an example to understand the concept of missing return statement error in method.

MissingReturnStatementExample1.java

Output

Java missing return statement

How to resolve the error?

There are two ways through which we can solve the error.

  1. By using void return type
  2. By adding a return statement

Java missing return statement

Both of these two ways are helpful only when we get this error in the method.

By using void return type

In the above code, we have created the diff() method in which we have declared return type as int. In this method, we didn’t use the return statement, and due to which the diff() method throws the missing return statement. So, we will solve the problem by simply changing the return type to void without providing any return statement like as:

Let’s compile and run the above code.

Java missing return statement

By adding a return statement

Another way of resolving this error is simply adding the return statement to the method. We will return the difference of the numbers using the return keyword like:

The above program shows the following output.

Output:

Java missing return statement

Missing return statement error within if / while / for

The second case is quite different from the first case. In a method, when we use the return statement inside the if statement, or for loop or while loop but doesn’t use the return statement at the end of the method, it throws the missing return statement error.

Let’s take an example to understand it.

MissingReturnStatementExample2.java

Output

Java missing return statement

How to resolve the error?

In order to solve the missing return statement error, we simply need to add the return statement to the method just like to the one we did in case one. So, we will return the some value of the same type which we used before the name like as:

Let’s compile and run the above program.

Output:

Java missing return statement


In Java, missing return statement is a common error which occurs if either we forget to add return statement or use in the wrong scenario.

In this article, we will see the different scenarios whenmissing return statement can occur.

Table of Contents

  • Missing return statement
  • Scenario 1
    • Solution
  • Scenario 2
    • Solution

Here are the few scenarios where we can get Missing return statement error.

Scenario 1

Let’s take an example, where we have a method that returns absolute value of the given positive number. In this example, we computed the absolute value but forgot to return it. When we compile this code, the compiler reports an error. See the example and output.

class Main {

    static int getAbsolute(int val) {

        Math.abs(val);

    }

    public static void main(String[] args){

        int a = 12;

        int result = getAbsolute(a);

        System.out.println(result);

    }

}

Output

Error: this method must return a result of type int

Solution

We can solve it by using two ways, either add return statement in the code or set return type as void in the method signature. See the examples below, wherein the first example we have added the return statement. We have also added another method getAbsolute2() and returned void from it in case we don’t want to return anything from the method.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

class Main {

    static int getAbsolute(int val) {

        return Math.abs(val); // adding return statement

    }

    // set void

    static void getAbsolute2(int val) {

        System.out.println(Math.abs(val));

    }

    public static void main(String[] args){

        int a = 12;

        int result = getAbsolute(a);

        System.out.println(result);

        getAbsolute2(a);

    }

}

Output:

12
12

Scenario 2

This error can also occur if we have used a return statement in if block. This return statement will execute only when if block executes. Since return statement depends on the if block condition, compiler reports an error. We have to either put return statement in else block or to the end of the method to resolve this.

class Main {

    static int getAbsolute(int val) {

        int abs_val = Math.abs(val);

        if(val>0)

            return abs_val;

    }

    public static void main(String[] args){

        int a = 12;

        int result = getAbsolute(a);

        System.out.println(result);

    }

}

This method must return a result of type int

Note: A method that has return type in its signature must have return statement.

Solution

If return statement is inside any block like if, for etc. then we need to add an extra return either in else block or in the last line of method body to avoid missing return type error. See the example and output.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

class Main {

    static int getAbsolute(int val) {

        int abs_val = Math.abs(val);

        if(val>0)

            return abs_val;

        return 0;

    }

    public static void main(String[] args){

        int a = 12;

        int result = getAbsolute(a);

        System.out.println(result);

    }

}

Output

0

That’s all about Missing return statement in java.

Содержание

  1. Missing return statement in java
  2. Missing return statement
  3. Scenario 1
  4. Solution
  5. Scenario 2
  6. Solution
  7. Was this post helpful?
  8. Share this
  9. report this ad Related Posts
  10. Author
  11. Related Posts
  12. [Fixed] Unsupported class file major version 61 in Java
  13. [Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
  14. [Fixed] java.util.HashMap$Values cannot be cast to class java.util.List
  15. [Fixed] Unable to obtain LocalDateTime from TemporalAccessor
  16. Java Hungry
  17. [Solved] Missing return statement in java error
  18. [Fixed] Missing return statement in java error
  19. 1. Method missing the return statement
  20. 2. Missing return statement error within if / while / for

Missing return statement in java

In Java, missing return statement is a common error which occurs if either we forget to add return statement or use in the wrong scenario.

In this article, we will see the different scenarios when missing return statement can occur.

Missing return statement

Here are the few scenarios where we can get Missing return statement error.

Scenario 1

Let’s take an example, where we have a method that returns absolute value of the given positive number. In this example, we computed the absolute value but forgot to return it. When we compile this code, the compiler reports an error. See the example and output.

Solution

We can solve it by using two ways, either add return statement in the code or set return type as void in the method signature. See the examples below, wherein the first example we have added the return statement. We have also added another method getAbsolute2() and returned void from it in case we don’t want to return anything from the method.

Scenario 2

This error can also occur if we have used a return statement in if block. This return statement will execute only when if block executes. Since return statement depends on the if block condition, compiler reports an error. We have to either put return statement in else block or to the end of the method to resolve this.

Note: A method that has return type in its signature must have return statement.

Solution

If return statement is inside any block like if , for etc. then we need to add an extra return either in else block or in the last line of method body to avoid missing return type error. See the example and output.

That’s all about Missing return statement in java.

Was this post helpful?

Cannot find symbol Java

[Fixed] bad operand types for binary operator in java

[Fixed] Unsupported class file major version 61 in Java

Table of ContentsReason for Unsupported class file major version 61 in JavaSolution for Unsupported class file major version 61 in JavaAndorid studio/Intellij Idea with gradleAny other scenario In this post, we will see how to fix Unsupported class file major version 61 in Java. Reason for Unsupported class file major version 61 in Java You […]

[Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

Table of ContentsReason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListFixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListUse ArrayList’s constructorAssign Arrays.asList() to List reference rather than ArrayList In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList. ClassCastException is runtime exception which indicate that code has tried to […]

[Fixed] java.util.HashMap$Values cannot be cast to class java.util.List

Table of ContentsWhy HashMap values cannot be cast to list?Fix for java.util.HashMap$Values cannot be cast to class java.util.List In this post, we will see how to fix error java.util.HashMap$Values cannot be cast to class java.util.List. Why HashMap values cannot be cast to list? HashMap values returns java.util.Collection and you can not cast Collection to List […]

[Fixed] Unable to obtain LocalDateTime from TemporalAccessor

Table of ContentsUnable to obtain LocalDateTime from TemporalAccessor : ReasonUnable to obtain LocalDateTime from TemporalAccessor : FixLocalDate’s parse() method with atStartOfDay()Use LocalDate instead of LocalDateTime In this article, we will see how to fix Unable to obtain LocalDateTime from TemporalAccessor in Java 8. Unable to obtain LocalDateTime from TemporalAccessor : Reason You will generally get […]

Источник

Java Hungry

Java developers tutorials and coding.

[Solved] Missing return statement in java error

The missing return statement in java error is mostly faced by beginners. You can familiarize yourself with these kinds of common errors by coding simple java projects. Let’s understand the error first. This error occurs at compile-time. The root cause of the error as the name suggests when the return statement is missing in the program.

[Fixed] Missing return statement in java error

1. Method missing the return statement

I am using the HelloWorld java program as an example. If you compile the above code using below command

you will get the missing return statement error. There are two ways to fix it.

1.1 In printHelloWorld() method we have declared return type as String. But if you notice there is no return statement inside the printHelloWorld() method. Just add that as shown below.

Now compile and run your program using commands below

Yahoo!! your problem is resolved.

1.2 The above situation can also be solved by changing the return type to void without providing any return statement.

Now compile and run your program using below commands

Yahoo!! your problem is resolved.

2. Missing return statement error within if / while / for

If you declare return statement inside if / while / for but not at the end of the method containing them, then you will get missing return statement error as shown below.

If you compile the above code then you will get missing return statement error.

Fix it by adding the return statement for the method similar to the one we did in case 1 above i.e adding line return «Alive is Awesome»;

There is a special case, what happens when you provide return statements inside both if/else block, as shown below. What will be the output?

The above code will compile fine and you will get the following output:

That’s all for today. Please mention in comments in case you have any questions related to missing return statement in java error.

Источник

The missing return statement in java error is mostly faced by beginners. You can familiarize yourself with these kinds of common errors by coding simple java projects. Let’s understand the error first. This error occurs at compile-time. The root cause of the error as the name suggests when the return statement is missing in the program.

Read Also: Fix illegal start of expression error in java

[Fixed] Missing return statement in java error

1. Method missing the return statement

public class HelloWorld 

   public static String printHelloWorld() {  
     System.out.println("HelloWorld from JavaHungry!");
   }
 
   public static void main(String args[]) {
     printHelloWorld();
   }
}

I am using the HelloWorld java program as an example. If you compile the above code using below command

javac HelloWorld.java

you will get the missing return statement error. There are two ways to fix it.

1.1 In printHelloWorld() method we have declared return type as String. But if you notice there is no return statement inside the printHelloWorld() method. Just add that as shown below.

public static String printHelloWorld() {
    System.out.println("HelloWorld from JavaHungry!"); 
    return "Alive is Awesome";      
}

Now compile and run your program using commands below

javac HelloWorld.java 
java HelloWorld

Yahoo!! your problem is resolved.

HelloWorld from JavaHungry!

1.2 The above situation can also be solved by changing the return type to void without providing any return statement.

public static void printHelloWorld() {
    System.out.println("HelloWorld from JavaHungry!"); 
}

Now compile and run your program using below commands

javac HelloWorld.java 
java HelloWorld

Yahoo!! your problem is resolved.

HelloWorld from JavaHungry!

2.  Missing return statement error within if / while / for

If you declare return statement inside if / while / for but not at the end of the method containing them, then you will get missing return statement error as shown below.

/**
 * Java program to demonstrate 
 * Missing return statement in java error
 * inside if / while / for
 * @author Subham Mittal
 */ 
public class HelloWorld 
{
    public static String printHelloWorld() {
        int i = 0; 
        if (i == 0) {
            return "inside if block";
        }
        for ( i=0; i < 9 ;i++) { 
            return "inside for loop";
        }
        while (i < 9) { 
            return "inside while loop"; 
        } 
        //Missing return statement for method    
     }
    public static void main(String args[]) {
        printHelloWorld();
    }
} 

If you compile the above code then you will get missing return statement error.

Fix it by adding the return statement for the method similar to the one we did in case 1 above i.e adding line return «Alive is Awesome»; 

Note: Assuming the return type of method is not void. You must provide the return statement for the method, which should be the last statement in the method.

There is a special case, what happens when you provide return statements inside both if/else block, as shown below. What will be the output?

public class HelloWorld 
{
    public static String printHelloWorld() {
        int i = 0; 
        if (i == 0) {
            return "inside if block";
        }
        else { 
            return "inside else block"; 
        } 
    }
    public static void main(String args[]) {
        printHelloWorld(); 
        System.out.println("HelloWorld from JavaHungry!");          
    }
}

The above code will compile fine and you will get the following output:

HelloWorld from JavaHungry!

That’s all for today. Please mention in comments in case you have any questions related to missing return statement in java error.

There are many types of errors that can be encountered while writing a Java Program. The errors can be with the Syntax or the Semantics of the Java program. The Java Community tries hard to avoid these errors at compile time itself, so that a programmer does not have to run the program to encounter the error. Use of generics is one way by which Java provides Type Safety by throwing errors at compile time itself.

One of those compile errors is the Missing return statement Error. This error can be caused by, as the error name suggests, when the return statement is missing from the program.

Missing return statement error can be thrown due to the following possible reasons:

Reason 1:

A method does not have a return statement, while the declaration requires one.

public String returnTest() {

System.out.println(«Return Test»);

}

The declaration states that the method returnTest() returns a String value, but because in the declaration no return statement is provided, the compiler throws the Missing return Statement Error.

How to Solve?

This Error can be resolved by providing a return statement if the code requires one.

public String returnTest() {

System.out.println(«Return Test»);

String ans = «Test returned»;

return ans;

}

Or, declaring the return value of the function as void.

public void returnTest() {

System.out.println(«Return Test»);

}

Reason 2:

One of the paths of the program execution does not return a value.

When we write a return statement inside a for/while/if statement, and one of the path of the program execution does not return a value, we get the Missing return statement value.

public String returnTest(Boolean printOrNot) {

System.out.println(«Return Test»);

String ans = «Test returned»;

if (printOrNot)

return ans;

}

This program would return the ans only if the printOrNot value is true.

This would return a Missing return statement Error.

How to Solve?

To correct this error, as a rule of thumb always return a default statement before the end of the last curly bracket for the method declaration.

public String returnTest(Boolean printOrNot) {

System.out.println(«Return Test»);

String ans = «Test returned»;

if (printOrNot)

return ans;

return «»;

}

Now I hope you got idea how to solve this error. Comment down below if you still have any queries.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error missing resource file
  • Error missing required parameters sitekey
  • Error missing required parameter q
  • Error missing required argument search query
  • Error missing radix parameter radix

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии