Calling a void method with parameters in Java follows the same basic principle as calling any method, but since it’s a void method, it does not return any value. The parameters allow you to pass data into the method, which the method can then use to perform its operations. Here’s a step-by-step guide on how to define and call a void method with parameters:
Step 1: Define a Void Method with Parameters
First, you define a void method within a class. This method can accept any number of parameters, which are specified within the method’s parentheses. Parameters act as variables within the method, and you can use them to perform operations or manipulate data within the method.
public class MyClass {
// A void method with a single parameter
public void printMessage(String message) {
System.out.println(message);
}
// A void method with multiple parameters
public void printSum(int num1, int num2) {
int sum = num1 + num2;
System.out.println("The sum is: " + sum);
}
}
Step 2: Create an Instance of the Class (for Non-static Methods)
To call a non-static void method, you need an instance of the class to which the method belongs. If the method is static, you can skip this step and call the method directly on the class.
public class TestClass {
public static void main(String[] args) {
// Creating an instance of MyClass
MyClass myObject = new MyClass();
}
}
Step 3: Call the Void Method with Arguments
Now, you use the instance of the class (or the class itself for static methods) to call the void method. You must pass arguments to the method that match the types and order of the parameters defined in the method.
public class TestClass {
public static void main(String[] args) {
// Creating an instance of MyClass
MyClass myObject = new MyClass();
// Calling the void method with a single argument
myObject.printMessage("Hello, Java!");
// Calling the void method with multiple arguments
myObject.printSum(5, 7);
}
}
Output
Hello, Java!
The sum is: 12
Key Points to Remember
- When calling a void method with parameters, ensure that the arguments passed to the method match the expected parameter types.
- If the method is non-static, you need an instance of the class to call the method. If the method is static, call it using the class name.
- Void methods do not return any value, so you cannot assign the result of a void method call to a variable.
Calling void methods with parameters is a common practice in Java for executing operations that require input data but don’t need to return any data to the caller.