void
Keyword in Java
In Java, the void
keyword is used to indicate that a method does not return any value. It's a fundamental part of method declarations, especially when you want a method to perform an action (like printing, updating, or processing something) but not send a result back to the caller.
Why Do We Use void
in Java?
Think of void
as your way of saying: "Hey, this method is going to do something, but you don’t need to expect a result from it." It's a design choice that keeps your code clean, organized, and intention-driven.
Syntax of a void Method
accessModifier void methodName() {
// method body
}
Example 1: A Simple void Method
public class HelloWorld {
public static void greet() {
System.out.println("Hello, world!");
}
public static void main(String[] args) {
greet(); // Calling the method
}
}
Hello, world!
Here, the method greet()
does not return anything. It simply performs an action — printing a message.
Example 2: void Method with Parameters
public class MathUtils {
public static void printSum(int a, int b) {
System.out.println("Sum: " + (a + b));
}
public static void main(String[] args) {
printSum(5, 7);
}
}
Sum: 12
This method accepts parameters and performs a calculation, but since it’s declared with void
, it doesn’t return the result — it just prints it.
Can a void Method Use return
?
Yes, but with a twist. In a void
method, you can use the return;
statement only to exit early — not to return a value.
public class ConditionalReturn {
public static void checkAge(int age) {
if (age < 18) {
System.out.println("You are underage.");
return;
}
System.out.println("You are eligible.");
}
public static void main(String[] args) {
checkAge(15);
checkAge(21);
}
}
You are underage.
You are eligible.
Notice how return;
exits the method early without returning any data. This is useful for breaking out of the method under specific conditions.
What Happens If You Try to Return a Value in a void Method?
Java won’t allow it. You’ll get a compile-time error like this:
public static void brokenMethod() {
return 42; // ERROR! Can't return a value from a void method.
}
Error Message
error: incompatible types: unexpected return value
void vs return Type Comparison
Aspect | void Method | Method with Return Type |
---|---|---|
Returns a value? | No | Yes |
Used for actions like printing/logging? | Yes | Sometimes, but usually for computations |
Can use return; ? |
Yes (without value) | Yes (with value) |
Example | void show() |
int add(int a, int b) |
Best Practices for Using void
- Use
void
when your method performs an operation but doesn't need to pass data back. - Avoid making methods
void
if you’re relying on their output for further processing. - Keep
void
methods focused on side effects like printing, logging, or updating UI or state.
Comments
Loading comments...