Method Declaration and Invocation in Java
Methods are blocks of code that perform a specific task. They are defined and invoked within classes in Java. Let's explore the declaration and invocation of methods in-depth.
Method Declaration:
A method in Java is declared using the following syntax:
returnType methodName(parameter1Type parameter1Name, parameter2Type parameter2Name, ...) {
// Method body
// Code to perform the task
return returnValue; // If the method has a return type
}
The returnType specifies the type of value that the method returns. If the method doesn't return a value, use void. methodName is the name of the method, and parameters are optional.
Method Invocation:
Methods are invoked (called) to execute the code inside them. Invocation is done using the following syntax:
returnType result = methodName(argument1, argument2, ...);
The returnType specifies the type of value that the method returns. If the method doesn't return a value, use void. methodName is the name of the method, and arguments are the values passed to the method.
Example:
Let's look at an example of a method that adds two numbers:
public class Calculator {
public int add(int num1, int num2) {
return num1 + num2;
}
}
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
int result = calculator.add(5, 3);
// Result: 8
}
}
Note:
Methods are a fundamental part of Java programming, allowing for code organization, reusability, and abstraction. Pay attention to access modifiers, return types, and parameters when declaring and invoking methods.