First, let’s get familiar with the syntax, examples, and finally the implementation.
Methods in Java are very important because they allow the same code to be reused, reducing the number of statements that need to be written in the code.
There are three main parts of the method to make it executable.
Declaration of method.
Definition of method.
Call this method.
Method invocation is the last step, while the other two steps are interchangeable. The only thing to remember is that you must declare a method before calling it.
To create a method without any parameter and return type, the following syntax is considered.
Class class_name{ function _name() { Statement 1; Statement 2; . . Statement n; //an optional return return; } Main function() { // invoking the above function function_name(); } }
A method to create an empty parameter list in a class. Statements are written inside the method, and an empty return statement may be added at the end. Then call this method in the main method.
The following program is to show how to create a method with neither parameters nor return type.
A class named Wish is created within which, a named method wish() with return type void is created denoting it does not return any value, also it does not consist of any parameter. A statement is written within the wish() method and is displayed by invoking this method in the main method.
// Java Program to demonstrate a method without Parameters and Return Type public class Wish { // Declaration and Definition of the method public static void wish(){ System.out.println("Good Morning! Have a nice day"); } public static void main(String args[]){ // Calling the method without any parameters wish (); } }
Good Morning! Have a nice day
The following program is to show how to create a method with neither parameters nor return type.
A class named Wish is created within which, a named method wish() with return type void is created denoting it does not return any value, also it does not consist of any parameter. The statements written inside the wish() method are displayed by invoking the method in the main method.
// Java Program to demonstrate a method without Parameters and Return Type public class Wish { // Declaration and Definition of the method public static void wish(){ System.out.println("Congratulations! Have a great professional life"); //It is optional to use a return statement here. return; } public static void main(String args[]){ // Calling the method without any parameters wish(); } }
Congratulations! Have a great professional life
This article explains how to define a method without parameters and return value in Java. We started with the syntax and further saw an example and two Java programs to get a clear understanding of the topic.
The above is the detailed content of Java program example: a method with no parameters and return type. For more information, please follow other related articles on the PHP Chinese website!