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
Frequently Asked Questions (FAQ)
Q1. What is the return statement in Java?
A statement that ends the current method and returns control to the caller. In non-void methods it also returns a value of the declared return type.
Q2. Can a void method use return?
Yes, a bare return; exits a void method early. It cannot return a value.
Q3. What does "missing return statement" mean?
The compiler found a path through a non-void method that ends without returning a value or throwing an exception. Add a final return or make sure every branch returns.
Q4. Can a method have more than one return statement?
Yes. Only one of them runs in each call. Multiple returns are common in guard clauses and searches.
Q5. How can a method return multiple values?
Return an object that holds them, ideally a record such as record MinMax(int min, int max). Arrays, lists and maps also work but are less descriptive.
Q6. Does finally run after return?
Yes. If a return runs inside try or catch, the finally block runs before the method actually returns. Only System.exit() or a JVM crash prevents it.
Q7. What happens if finally also has a return?
The return in finally wins: it replaces the earlier return value and discards any pending exception. This hides bugs, so never return from finally.
Q8. Can I return null from a method?
Yes, for reference types, but callers may forget to check it. Prefer returning an empty collection, an empty string or an Optional.
Q9. Can a constructor have a return statement?
Only a bare return; to exit early. Constructors have no return type and cannot return a value.
Q10. What is the difference between return and break?
return leaves the whole method; break leaves only the innermost loop or switch and continues with the rest of the method.
Q11. Can I write code after a return statement?
Not in the same block; it would be unreachable and the compiler rejects it. Code in other branches is fine.
Q12. Can the main method return a value?
No, the standard main is void. To report a status code to the operating system, call System.exit(code).
Q13. What does return do inside a lambda?
It returns from the lambda only. In list.forEach(x -> { if (x == null) return; ... }), return skips that element; it does not end the enclosing method.
Q14. Can a method return an array?
Yes: declare the return type as an array, such as int[] getScores(), and return an array of that type.
Q15. What is an early return?
Returning from a method as soon as the result is known or the input is invalid, instead of running the rest of the method. It reduces nesting and unnecessary work.
Q16. Can a return type be a superclass or interface?
Yes. A method declared to return List<String> can return an ArrayList or any other implementation. Overriding methods may also narrow the return type (covariant return types).
Q17. What is a covariant return type?
When an overriding method returns a subtype of the parent method's return type, for example a parent returning Animal and a child returning Dog. Java allows this since Java 5.
Q18. Should I use return or yield in a switch?
Use yield to give a switch expression its value. return inside a switch statement leaves the whole method.
Q19. Is it better to have a single return point?
The old "single exit" rule came from languages without automatic clean-up. In Java, with garbage collection and try-with-resources, multiple well-placed returns usually make methods clearer.
Q20. Can return be used to exit a loop?
Yes. A return inside a loop ends the loop and the method together, which is a common way to stop a search once the result is found.