In Java, methods can perform actions but not return any value. These methods are declared with the void
keyword. Calling a void method simply involves using the method’s name followed by parentheses (()
) and any required arguments inside those parentheses. You do not expect a return value from a void method, so you can’t assign the result of the method call to a variable.
Syntax of a Void Method
Here is an example of how a void method is declared within a class:
public class MyClass {
// A void method with no parameters
public void displayMessage() {
System.out.println("Hello, World!");
}
// A void method with parameters
public void displayCustomMessage(String message) {
System.out.println(message);
}
}
In this example, displayMessage
is a void method that prints a simple message to the console, and displayCustomMessage
is a void method that prints a custom message passed as an argument.
Calling a Void Method
To call a void method, you first need an instance of the class (unless the method is static, in which case you can call it on the class itself). Here’s how you can call the void methods defined in MyClass
:
public class TestClass {
public static void main(String[] args) {
// Create an instance of MyClass
MyClass myObject = new MyClass();
// Call the void method without parameters
myObject.displayMessage(); // Outputs: Hello, World!
// Call the void method with a parameter
myObject.displayCustomMessage("Goodbye, World!"); // Outputs: Goodbye, World!
}
}
Static Void Methods
If a method is declared as static
, you don’t need an instance of the class to call it. Instead, you call it on the class itself:
public class MyClass {
// A static void method
public static void displayStaticMessage() {
System.out.println("This is a static message.");
}
}
public class TestClass {
public static void main(String[] args) {
// Call the static void method
MyClass.displayStaticMessage(); // Outputs: This is a static message.
}
}
Key Points
- Void methods are declared with the
void
keyword and do not return a value. - Call a void method with its name followed by parentheses, including any arguments if the method requires them.
- For non-static methods, you need an instance of the class to call the method. For static methods, call them on the class itself.
- Void methods are often used to perform actions like displaying messages or modifying the state of an object without directly returning a value.
Calling void methods is a fundamental aspect of Java programming, allowing for modular, reusable code that can perform a variety of tasks within an application.