⬅ Previous Topic
Java try KeywordNext Topic ⮕
Java volatile Keyword⬅ Previous Topic
Java try KeywordNext Topic ⮕
Java volatile Keywordvoid
Keyword in JavaIn 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.
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.
accessModifier void methodName() {
// method body
}
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.
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.
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.
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: incompatible types: unexpected return value
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) |
void
when your method performs an operation but doesn't need to pass data back.void
if you’re relying on their output for further processing.void
methods focused on side effects like printing, logging, or updating UI or state.⬅ Previous Topic
Java try KeywordNext Topic ⮕
Java volatile KeywordYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.