In Java, we can call a method or function by using the name of the method followed by parentheses, optionally containing any required arguments.
Following are the steps to call a method in Java:
- Define the method: First, we need to have a method defined in our Java class. The method can be a part of the same class or another class (in which case we may need to create an instance of that class).
- Create an object (if needed): If the method is an instance method (i.e., not declared as static), we’ll need to create an object of the class that contains the method.
- Call the method: Once we have the method, we can call the method
Step-by-step example:
Suppose we have a simple Java class named Calculator
with an add
method:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
Now, to call the add
method, we can follow these steps:
- Create an object of the
Calculator
class (sinceadd
is an instance method)
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator(); // Create an object of the Calculator class
// Rest of the code goes here
}
}
- Call the
add
method using the object
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
int result = calculator.add(5, 3); // Call the add method with arguments 5 and 3
System.out.println("Result: " + result); // Output: Result: 8
}
}
That’s it! The add
method is now called with the arguments 5
and 3
, and the result is printed to the console.
If the method is declared as static
, we can call it without creating an instance of the class.
For example:
public class MathUtils {
public static int multiply(int a, int b) {
return a * b;
}
}
Now, we can call the multiply
method directly using the class name:
public class Main {
public static void main(String[] args) {
int result = MathUtils.multiply(5, 3); // Call the multiply method with arguments 5 and 3
System.out.println("Result: " + result); // Output: Result: 15
}
}
There is one thing to remember that the method we are calling must be visible (public or class is in the same package) from the context we are calling it.