How to exit a method in Java (return, exceptions and loops)
Codemia Knowledge Hub ·
Use the return statement. In a method with a return type it exits and hands a value back to the caller; in a void method a bare return; simply exits. A method also exits when it throws an exception or reaches the end of its body.
Exiting with return
Exiting by throwing an exception
Throwing an exception exits the current method immediately and transfers control to a matching exception handler, if one exists. Use it to signal abnormal conditions.
Reaching the end of the method
A void method exits naturally after its last statement, with no explicit return needed:
A method with a non-void return type must return a value on every path. Reaching the end of it without returning one is a compilation error.
Returning from inside a loop
A conditional return inside a loop leaves the whole method as soon as the condition is met, not just the loop:
Here the method exits the moment the target is found, so "Target not found" only prints when the loop finishes without a match.
| Technique | Description | Usage Example |
return statement | Exits method naturally, optionally returning a value | return a + b; |
| Exception throwing | Exits method due to abnormal state, passing control to handlers | throw new IllegalArgumentException("message"); |
| End of method block | Implicit method exit after last statement in void methods | System.out.println("Done"); // Exits implicitly |
return in loops | Exits method during loop execution if certain conditions are met | if(condition) return; // Exits method |
Why exit early
- Performance: Returning early skips unnecessary work, especially in loops.
- Readability: A well-placed exit makes it clear which conditions end the method.
- Error handling: Exceptions enforce strict error handling without cluttering your logic with conditional checks.
Related reading
- How to brew install java?
- How to build an APK file in Eclipse?
- How to build JARs from IntelliJ IDEA properly?
- How to build sources JAR with Gradle?
- How to cache results of a Spring Data JPA query method without using query cache?
- How to calculate elapsed time from now with Joda-Time?
- How to call a method after a delay in Android
- How to call a method with a separate thread in Java?
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.