Invalid Method Declaration; Return Type Required in Java

posted 7 min read

Introduction

If you are getting the error "invalid method declaration; return type required" after you have compiled your Java code, although you have defined the classes and their methods properly, you’ve come to the right place. Being a statically typed language, Java supports various built-in data types. Sometimes, you have defined the classes and methods of the respective classes properly but as soon as you compile the code, you encounter the error of " invalid method declaration; return type required".
Are you curious about why it happens? The major reason is that no return type is mentioned while declaring the method and the Java compiler always expects something in return as a return value or else you must make the function a void if there is no need for a return value which is the cause of error invoke. So, in this article, I am going to cover significant areas ranging from the cause of this error to the steps to reproduce and provide an efficient and optimized solution to resolve the error.

Error Demonstration

Step 1: Code Editor: Open Your Code Editor

To begin demonstrating the error with me, you just need to open your favorite code editor. I prefer to use OnlineGDB compiler.

Step 2: Copy Code: Copy the Errored Code

Copy the code below and paste it into the editor.


    class SumClass // Class other than main that have function
    {
      sumMethod () //method without any return type or void
      {
           System.out.println ("Hello World from SumClass"); // does not print any this because of error
      }
    }
    public class Main // main class 
    {
      public static void main (String[]args)
      {
          System.out.println ("Hello World"); //printing on screen
          SumClass sumObject = new SumClass (); // creating an instance of class
          sumObject.sumMethod (); // calling the method of that class
      }
    }

Step 3: Code Compilation: Compile the Errored Code

Now, you just need to compile the code. If you are with me and using the OnlineGDB, simply click on run and the code starts compiling.

Step 4: Output Observation: See the Error After Compilation

Once your code is compiled, you will be able to see the compilation results and the following error:

image

Why This Error Occurred?

  • As Java is a statically typed language while defining the methods inside the classes, Java gives an error if no return type is specified for the method. So, there should be a specified proper return type depending on what is the intention of the method being implemented and what kind of data the method wants to return after completing its execution. If the method executed hundreds to thousands of lines of code to perform any complex calculation and did not return anything after exiting itself, the method would be of no use. So, Java helps to monitor this error and makes it mandatory to specify the return type at the start of method declarations. You might have seen cases where we simply print the result of the method inside its definition and are not required to return its value. For such cases, you should use void as discussed below.
  • Java expects the methods to return any value while exiting itself. That return could be in the form of integer (int), character (char), floating (float), or even user-defined data types or objects. The return type depends on the result of the method after executing all the lines of code that the method holds. The value return can be assisted in executing the rest of the code either using loops, conditional statements or even passing the return value to other function(s).
  • If the method is not returning anything, you should specify void at the start of the method declaration before the method name. As for the sumMethod, you can use int sumMethod to show that the value returned will be of type int after the execution of the definition of sum method.

How to Resolve the Invalid Declaration Error?

Resolving this error is quite short and simple. You just need to mention the data type at the start of the method declaration. This data type can be either built-in (primitive) or user-defined. As we know, Primitive data types are the data types that Java implements by default and the programmer just needs to use them to declare the variables. On the other hand, user-defined data types are those which the user/programmer can define with the help of primitive data types. For example, you can define the data type for Person by combining both name (data type String) and age (data type int).

For Instances:

  • int sumMethod(){}
  • float sumMethod(){}

Returning Nothing?

There is a possibility, as it happened above in our case, that the method is not returning anything as such and just printing "Hello World From SumClass" on the console. For such cases, you need to mention void keyword at the start of the method declaration as shown below.

  • void sumMethod() {}

Error Resolved Code

To resolve the error of "invalid method declaration; return type required", you just have to specify the return type as shown below:


    class SumClass // Class other than main that have function
    {
     void sumMethod () //method now specify with void as return type
      {
           System.out.println ("Hello World from SumClass"); // does not print any this because of error
      }
    }
    public class Main // main class 
    {
      public static void main (String[]args)
      {
          System.out.println ("Hello World"); //printing on screen
          SumClass sumObject = new SumClass (); // creating an instance of class
          sumObject.sumMethod (); // calling the method of that class
      }
    }

Note: Remember that while dealing with void method, there is no need to return anything.

Output After Successful Compilation

Nice look, yep?

image

Similar Example With int Data Type


Let's discuss a similar example, which return int instead of void. I want to share most of the cases with you so that you encounter less of this type of issue.


Code

class SumClass // another class declaration for sum of two numbers
{
  int sumMethod (int num1, int num2) // method that take two integer number
  {
      return num1 + num2; //this will return the sum of two number
  }
}
 
public class Main //main class 
{
  public static void main (String[]args)
  {
      System.out.println ("Hello World"); //this line print on the screen before the sum displayed
      SumClass sumObject = new SumClass (); //here the instance of the class is created
      int resultInt = sumObject.sumMethod (4, 5); //using the instance method is called
      System.out.println ("Sum for Int: " + resultInt); //this will print the final sum result on screen
  }
}

Note: Remember to write the int datatype if the function returns integer value, you can change it if you are using some other datatype like float, char

Output
image


FAQs
Q: What is return type in Java?
A: The return type is the type of data that contains the value returned by the method and should be compatible with the type of method during declaration.

Q: What is void type in Java?
A: As we know, void means nothing so in Java, when we declare a method that does not require anything in return at that time void type is used.

Q: Is int return type mostly used?
A: Yes, when the method has mostly math calculations and has to return some integer return value so this time int return type is used.

Conclusion

As we know, the java programming language is the one that strictly follows the type-checking and other paradigms of programming. So, when we create a function in Java, the compiler always expects something in return. However, because of some frequent coding and changes, developers mostly made mistakes in returning at the end of the function which caused this error. So, in short, always remember to check your methods to make sure you tell Java what to expect in return at the end of a function. That approach will put your coding hurdles aside and make the process smooth, so Happy Coding!


Reference

Java Return Types

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

Checked exception is invalid for this method

prince yadav - Nov 26, 2023

[SOLVED] Void type not allowed here

prince yadav - Nov 26, 2023

Class is Not Abstract & Does Not Override Abstract Method - Fixed

Abdul Daim - Feb 24

Solved Incompatible types: possible lossy conversion from double to int

prince yadav - Oct 14, 2023

ValueError: dictionary update sequence element #0 has length 1; 2 is required (Solved)

Tejas Vaij - Mar 10
chevron_left