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
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:
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");
}
}
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:
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));
}
}
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
elseblocks. - A
returninside a loop ends both the loop and the method. - Every possible path through a non-void method must end in a
returnor athrow; otherwise the compiler reports "missing return statement". That is whyindexOfends withreturn -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:
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());
}
}
loading... closing resources result: data risky() = 1
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:
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"));
}
}
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
voidmethod cannot return a value (return 5;is an error), and a non-void method cannot use a barereturn;. - Statements directly after
returnin 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,
returnreturns from the lambda, not from the surrounding method. - In a switch expression, use
yieldinstead ofreturnto produce the switch's value. - Returning
nullfor "no result" is legal but error-prone; prefer empty collections orOptional.
7. return vs break vs continue
| Statement | Exits | Returns a value? |
|---|---|---|
return | The whole method | Yes (unless the method is void) |
| break | The innermost loop or switch | No |
| continue | The current loop iteration | No |
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.
finallyruns before the method returns; never return fromfinally.- Return several values with a record, and "maybe a value" with
Optional.
Related Tutorials
Reference: Oracle Java Tutorials: Returning a Value from a Method