Method is a block of code that helps the user achieve specific functionality. Methods are very important because they help prevent code duplication because we can call them whenever we require that functionality. In Java, a method has to be a part of a class, it cannot be placed on its own.
Following are the modifiers you can use with a method:
Depending on the return type there are two types of methods:
method that returns a value.
method that will not return a value.
Depending on the parameters there are two types of methods:
method with parameters
method without parameters.
Rules for defining a method
The return type of the method should be void if the method is not returning anything. The return type cannot be blank.
For a method with void return type, there is no need to use return statement. It can have an empty return statement without any value like this”
If the method is returning a value, the return type should not be void and should be a data type compatible with the value being expected.
If the method is returning a value, the return statement must be included as the last statement followed by the returning value. For eg.
return string; //where string is a variable evaluating to something
A method can have any number of return statements but conditionally only one of them should evaluate to true. For eg in the below program to check if a number is odd or even there are two return statements but only one of them will be true at a time.
A method needs to have a parameter(s) if the caller wants to provide a value dynamically to the method. For e.g. in the above program, the text inside the bracket (int num) is called a parameter. The method is of no use without that value.
The caller of the method needs to provide the argument while calling the method if the method being called is having a parameter. For eg in the above method oddEven(), some code should be there which will provide the value of the num variable. Suppose the code is:
If a method has more than one parameters then the datatype, order and the number of arguments must be the same while calling the method. The argument can be of the same or compatible data types.