What is Method in Java?
It is one of the fundamental structure blocks of object-oriented programming in Java and is used to encapsulate a specific functionality or set of operations. Methods allow you to achieve actions, manipulate data, and execute algorithms within classes.
Method declarations generally consist of 6 components:
Create a Method
public int methodName() {
// body
}
Here,
- public − modifier
- int− return type
- methodName− the name of the method
The method definition consists of one method heading and one method body. The fundamental Java method syntax is as follows:
accessModifier returnType methodName() {
// Method body – the code that defines the behavior of the method
// It can include any valid Java statements and expressions
// Optionally, it may return a value using the “return” keyword if the returnType is not “void”
}
Call a Method
When you call a method, you are essentially instructing the program to execute the code inside that method, and it may or may not return a value depending on the method’s return type. Let’s explore how method-calling statements work:
The syntax to call a method in Java is as follows:
methodName();