Course contentsShow
← Java
Lesson 196 of 2,8705. Methods and Function CallsFree lesson

The return Statement: Early Exit and Value Propagation

Master using return to exit methods early and propagate values back to callers.

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:

  1. Early exit: It immediately terminates the method, even if there's more code below
  2. Value propagation: For non-void methods, 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.