void methods
- Java course
- Beginner
- Lesson 73/116
- 3 min
Learn valueless methods with void.
void methods
Some methods do not return a value; they just do an action. These are called void methods. The return statement is either omitted or written without a value.
static void printLine(String text) {
System.out.println("--- " + text + " ---");
}To exit a void method early, you can write return;. This is handy when you want to end the method as soon as a condition is met.
Early exit in void methods
Inside a void method you can write return; to leave the flow immediately. This is handy for skipping unnecessary work.
static void logIfPositive(int n) {
if (n <= 0) return;
System.out.println("Positive: " + n);
}Here, when n is negative or zero, the method prints nothing. This pattern avoids deep nested if blocks and keeps the code readable.
Practice Write a greeting method
Define a static void method called greet; parameter String name, body System.out.println("Selam " + name). Call greet("Ayşe") and greet("Mehmet") from main.
Starter code
public class Main {
public static void main(String[] args) {
// Call greet with Ayşe and Mehmet
}
// Define the greet method here
}Sample solution
static void greet(String name) {
System.out.println("Hello " + name);
}
// inside main:
greet("Ayşe");
greet("Mehmet");Expected output
Hello Ayşe Hello Mehmet
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: return type
static ____ printHello() {
System.out.println("Hello");
}
static void printHello() {
System.out.println("Hello");
}
Explanation: A method that returns no value is void.
2 Match scenario to return type
| Term | Meaning |
|---|---|
Print text to the screen |
void |
Product of two numbers |
int |
Average (decimal) |
double |
Is this user an admin? |
boolean |
3 What happens if we try to return a value from a void method?
- It causes a compile error
- It throws at runtime Correct answer
- The value is auto-converted to void
- The value is ignored
Explanation: A void method cannot return a value; it is a compile error.