What does the return keyword do in a void method in Java? What does the return keyword do in a void method in Java? java java

What does the return keyword do in a void method in Java?


It just exits the method at that point. Once return is executed, the rest of the code won't be executed.

eg.

public void test(int n) {    if (n == 1) {        return;     }    else if (n == 2) {        doStuff();        return;    }    doOtherStuff();}

Note that the compiler is smart enough to tell you some code cannot be reached:

if (n == 3) {    return;    youWillGetAnError(); //compiler error here}


You can have return in a void method, you just can't return any value (as in return 5;), that's why they call it a void method. Some people always explicitly end void methods with a return statement, but it's not mandatory. It can be used to leave a function early, though:

void someFunct(int arg){    if (arg == 0)    {        //Leave because this is a bad value        return;    }    //Otherwise, do something}


The keyword simply pops a frame from the call stack returning the control to the line following the function call.