The return Statement: Early Exit and Value Propagation
You'll learn how return both ends method execution immediately and sends values back to the caller.
What Does return Actually Do?
The return statement serves two critical purposes in Java methods:
- Early exit: It immediately terminates the method, even if there's more code below
- Value propagation: For non-
voidmethods, it sends a value back to whoever called the method
Think of return like handing over a baton in a relay race and stepping off the track—you pass control (and possibly a result) back to the caller and stop running.
Early Exit: Leaving Before the End
public void checkAge(int age) {
if (age < 0) {
System.out.println("Invalid age!");
return; // Exit immediately, skip the rest
}
System.out.println("Age is valid: " + age);
// This line never runs if age < 0
}
When return executes, the method stops right there. Any code after it in that execution path is skipped.
Value Propagation: Sending Results Back
public int multiply(int a, int b) {
return a * b; // Calculate and send result back
}
// When called:
int result = multiply(5, 3); // result receives 15
The return statement evaluates the expression (a * b) and delivers that value back to the calling code, where it can be stored, used in calculations, or passed elsewhere.
Multiple Returns in One Method
public int getAbsoluteValue(int num) {
if (num < 0) {
return -num; // Exit here if negative
}
return num; // Exit here if zero or positive
}
Key Takeaway: The return statement immediately exits a method and, for value-returning methods, propagates a result back to the caller—it's how methods communicate their output and control when they're done executing.