Open In App

Java Program to Illustrate a Method Without Parameters and Return Type

Functions are a way to break a program into different modules which are executed one by one. To use a function in Java we need to: 

It is important that we declare the function before calling it and the definition can be kept at any portion of the program.



Declaring, Defining and Calling a function

Now we will be creating a function with no return type and no parameters. While declaring a function we need to specify the return type of the functions and the number and types of parameters it is going to accept. For the return type, we have options such as int, float, char etc. But sometimes we don’t have to return anything in such scenario we have to use the void return type. And since we are not going to pass any parameter too, so we have to specify it while declaring by keeping the parenthesis empty. 



Example:




// Java Program to Illustrate a Method with No Parameters
// and Return Type
 
public class Main {
   
    // Declaration and Definition of the function
    public static void greet()
    {
        System.out.println(
            "Hey Geeks! Welcome to NoWhere.");
       
        /* Optional program will work same
           without this return statement */
        return;
    }
    public static void main(String args[])
    {
        // Calling of the function without any parameters
        greet();
    }
}

Output
Hey Geeks! Welcome to NoWhere.

The time complexity and auxiliary space are both constant, O(1).

In the above program, we declare and define the function at the same place which can be done and is also considered good if we want to use the function in the same program it is declared. Also, you can notice that the parameters during declaration and call are empty because we are not passing any parameters. Even we are not storing any data from the function because the function isn’t returning anything.

Note: A return statement can be used at the end of the function but it’s completely optional if you remove the return statement then to the program will run in the same manner as it does with the return statement.

Article Tags :