Skip to main content Skip to docs navigation
TechSpiderTutorials

Java void Keyword

In Java programming, the void keyword holds a specific meaning related to method declarations. It plays a crucial role in defining methods that do not return a value. This comprehensive guide delves into the usage, implications, and best practices associated with the void keyword in Java.

Definition and Usage

The void keyword in Java is used in method declarations to specify that the method does not return any value. This is particularly useful for methods that perform actions or tasks without producing a result that needs to be returned.

public void printMessage() {
    System.out.println("Hello, World!");
}

void indicates that printMessage() does not return any value.

It simply prints a message to the console without requiring any return statement.

Characteristics and Limitations

No Return Type: Methods declared with void do not return a value using the return statement. Attempting to return a value within a void method will result in a compilation error.

// Compilation Error: Cannot return a value from method with void return type
public void process() {
    return 10;
}

Method Invocation

When invoking a void method, you simply call the method name followed by parentheses, without assigning its return value to a variable.

public class Example {

public void doSomething() {
    // Perform some action
}

public static void main(String[] args) {
    Example example = new Example();
    example.doSomething(); // Method call
}
}

java ‘void’ Example

public class MathOperations {

public void printSum(int a, int b) {
    int sum = a + b;
    System.out.println("Sum: " + sum);
}

public static void main(String[] args) {
    MathOperations math = new MathOperations();
    math.printSum(5, 3); // Output: Sum: 8
}
}