Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 977
Relequestual Avatar asked Apr 13 '09 17:04

Relequestual


1 Answers

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 } 
like image 190
CookieOfFortune Avatar answered Sep 28 '22 11:09

CookieOfFortune