Low Orbit Flux Logo 2 F

Java How To Exit A Method

If you want to exit a method in Java you should use “return”. This works on both methods that return a value and on methods that don’t return a value.

Quick answer: Exit a method in Java like this:


return 0;    // use this in a non-void method
return;      // use this in a void method

In this example you can call return when the method is done or when an error is detected and you want to exit early.


public int method1() {          
    int result = 0;

    while( result < 100 ) {
        result = checkData();
        if( checkError() ) {
            return result;              // return early and exit method
        }
    }           
    return result;                      // return and exit at the end of the method
}

How to exit a void method in Java

It is possible to exit a method in Java even if it is void. Even though it is not required, you can still use “return” in a void method. Just don’t specify a value. See the example below.


public void method2() {
    while( result < 100 ) {
        checkData();
        if( checkError() ) {
            return;            // exit method
        }
    }
}