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.
Hey Geeks! Welcome to NoWhere.
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.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.