Relequestual Relequestual - 1 month ago 5
Java Question

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

I'm looking at a path finding tutorial and I noticed a

return
statement inside a
void
method (class
PathTest
, line 126):

if ((x < 0) || (y < 0) || (x >= map.getWidthInTiles()) || (y >= map.getHeightInTiles())) {
return;
}


I'm a novice at Java. Can anyone tell me why it's there? As far as I knew,
return
inside a void method isn't allowed.

Answer

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
}
Comments