Open In App

Java Program to Illustrate a Method Without Parameters and Return Type

Last Updated : 17 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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: 

  • Declare the function i.e. declare a prototype of the function.
  • Define the function
  • Call the function

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




// 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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads