In general, a way may be thanks to perform some task. Similarly, the tactic in Java may be a collection of instructions that performs a selected task. It provides the reusability of code. we will also easily modify code using methods. during this section, we'll learn what's a way in Java, sorts of methods, method declaration, and the way to call a way in Java.
What is Method in JAVA language?
A method may be a block of code or collection of statements or a group of code grouped together to perform a particular task or operation. It is wont to achieve the reusability of code. We can write a method once and use it many times. We don't require to write down code again and again. It also provides the straightforward modification and readability of code, just by adding or removing a piece of code. The method is executed only we call or invoke it.
The most important method in Java is that the main() method.
Method Declaration in JAVA.
The method declaration provides information about method attributes, like visibility, return-type, name, and arguments. It has six components that are known as method header, as we have shown in the following figure.
Method Signature: Every method has a method signature. It is a part of the method declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is that the access sort of the tactic. It specifies the visibility of the method. Java provides four types of access specifier:
Public: The method is accessible by all classes when we use public specifier in our application.
Private: once we use a personal access specifier, the tactic is accessible only within the classes during which it's defined.
Protected: once we use protected access specifier, the tactic is accessible within an equivalent package or subclasses during a different package.
Default: once we don't use any access specifier within the method declaration, Java uses default access specifier by default. It is visible only from an equivalent package only.
Return Type: Return type may be a data type that the tactic returns. It may have a primitive data type, object, collection, void, etc. If the tactic doesn't return anything, we use void keyword.
Method Name: it's a singular name that's wont to define the name of a way . It must be like the functionality of the tactic . Suppose, if we are creating a way for subtraction of two numbers, the tactic name must be subtraction(). A method is invoked by its name.
Parameter List: it's the list of parameters separated by a comma and enclosed within the pair of parentheses. It contains the data type and variable name. If the method has no parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed within the pair of curly braces.