00:00

return Statement in Java – Explained with Examples

The return statement ends a method and hands control back to the code that called it. In a method that produces a result, return also sends that result back; in a void method, a bare return; simply exits early.

This tutorial covers returning values of any type, early returns and guard clauses, returning from loops, how return interacts with finally, and the best ways to return more than one value.

1. Syntax

Two forms of return
return expression;   // in a method with a return type: sends a value back
return;              // in a void method or constructor: just exits

The type of the returned expression must match the method's declared return type (or be convertible to it, such as an int returned from a method declared to return long).

2. Returning Values

A method can return any type: a primitive, a String, a collection or your own objects. A void method returns nothing but can still use return; to stop early:

ReturnValues.java
import java.util.List;

public class ReturnValues {
    static int square(int n) { return n * n; }                    // returns an int
    static boolean isAdult(int age) { return age >= 18; }         // returns a boolean
    static String initials(String first, String last) {           // returns an object
        return "" + first.charAt(0) + last.charAt(0);
    }
    static List<String> topThree() { return List.of("gold", "silver", "bronze"); }

    static void greet(String name) {                               // void: no value
        if (name == null || name.isBlank()) {
            System.out.println("Hello, guest!");
            return;                                                // exit early
        }
        System.out.println("Hello, " + name + "!");
    }

    public static void main(String[] args) {
        System.out.println(square(9));
        System.out.println(isAdult(16));
        System.out.println(initials("Asha", "Verma"));
        System.out.println(topThree());
        greet("");
        greet("Ravi");
    }
}
Output
81
false
AV
[gold, silver, bronze]
Hello, guest!
Hello, Ravi!

3. Early Returns, Guard Clauses and Loops

A method can contain several return statements. Returning as soon as the answer is known keeps code flat and avoids unnecessary work:

EarlyReturn.java
public class EarlyReturn {
    // Guard clauses: handle bad input first, then the normal case
    static String withdraw(double balance, double amount) {
        if (amount <= 0) return "Rejected: amount must be positive";
        if (amount > balance) return "Rejected: insufficient funds";
        return "Approved: new balance " + (balance - amount);
    }

    // Returning from inside a loop ends the search immediately
    static int indexOf(int[] values, int target) {
        for (int i = 0; i < values.length; i++) {
            if (values[i] == target) return i;
        }
        return -1;                                   // every path must return a value
    }

    public static void main(String[] args) {
        System.out.println(withdraw(500, -10));
        System.out.println(withdraw(500, 800));
        System.out.println(withdraw(500, 200));
        System.out.println("index of 30: " + indexOf(new int[] {10, 20, 30, 40}, 30));
        System.out.println("index of 99: " + indexOf(new int[] {10, 20, 30, 40}, 99));
    }
}
Output
Rejected: amount must be positive
Rejected: insufficient funds
Approved: new balance 300.0
index of 30: 2
index of 99: -1
  • Guard clauses reject bad input first, so the normal path is not buried inside else blocks.
  • A return inside a loop ends both the loop and the method.
  • Every possible path through a non-void method must end in a return or a throw; otherwise the compiler reports "missing return statement". That is why indexOf ends with return -1.

4. return and finally

If a return is executed inside a try block, the finally block still runs before the method actually returns. The returned value is evaluated first and saved:

ReturnAndFinally.java
public class ReturnAndFinally {
    static String load() {
        try {
            System.out.println("  loading...");
            return "data";                     // finally still runs before the method returns
        } finally {
            System.out.println("  closing resources");
        }
    }

    static int risky() {
        int x = 1;
        try {
            return x;                          // the value 1 is saved here
        } finally {
            x = 99;                            // changing x does not affect the returned value
        }
    }

    public static void main(String[] args) {
        System.out.println("result: " + load());
        System.out.println("risky() = " + risky());
    }
}
Output
  loading...
  closing resources
result: data
risky() = 1
Never return from a finally block. A return inside finally replaces the value from try and silently swallows any exception that was being thrown. Most IDEs and compilers with -Xlint warn about it.

5. Returning More Than One Value

A Java method returns exactly one value, but that value can be an object that groups several results. Records are the cleanest way, and Optional expresses "a value or nothing" without null:

MultipleResults.java
import java.util.Optional;

public class MultipleResults {
    // Return several values by wrapping them in a record
    record Stats(int min, int max, double average) { }

    static Stats stats(int[] data) {
        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE, sum = 0;
        for (int d : data) {
            min = Math.min(min, d);
            max = Math.max(max, d);
            sum += d;
        }
        return new Stats(min, max, (double) sum / data.length);
    }

    // Return "maybe a value" with Optional instead of null
    static Optional<String> findUser(int id) {
        return id == 7 ? Optional.of("Meera") : Optional.empty();
    }

    public static void main(String[] args) {
        System.out.println(stats(new int[] {4, 9, 2, 7}));
        System.out.println(findUser(7).orElse("not found"));
        System.out.println(findUser(3).orElse("not found"));
    }
}
Output
Stats[min=2, max=9, average=5.5]
Meera
not found

Other options are arrays, collections and maps, but a named record makes the meaning of each value obvious.

6. Rules of return

  • A void method cannot return a value (return 5; is an error), and a non-void method cannot use a bare return;.
  • Statements directly after return in the same block are unreachable and do not compile.
  • Constructors can use return; to exit early, but cannot return a value.
  • In a lambda with a block body, return returns from the lambda, not from the surrounding method.
  • In a switch expression, use yield instead of return to produce the switch's value.
  • Returning null for "no result" is legal but error-prone; prefer empty collections or Optional.

7. return vs break vs continue

StatementExitsReturns a value?
returnThe whole methodYes (unless the method is void)
breakThe innermost loop or switchNo
continueThe current loop iterationNo

8. Summary

  • return value; ends a method and sends a result back; return; exits a void method.
  • Every path of a non-void method must return a value or throw an exception.
  • Early returns and guard clauses make methods easier to read.
  • finally runs before the method returns; never return from finally.
  • Return several values with a record, and "maybe a value" with Optional.

Related Tutorials

Reference: Oracle Java Tutorials: Returning a Value from a Method