views:

2537

answers:

6

Hi all. Looking a path finding tutorial here (http://www.cokeandcode.com/pathfinding) which i was linked to from SO :) good work people.

Working in integrating the code into my game, and i noticed a "return;" line inside a void method. class is PathTest on website, line 130.

I know im a novice at java, but can anyone tell me why its there? As far as I knew, return inside a void method isn't allowed.

Thanks in advance

Rel

+16  A: 

I just exits the function at that point. Code after it has returned is not run.

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();
}
CookieOfFortune
I understand your code is illustrative, but for the parent's info; I've worked with people that believe each method should only have a single return statement. I'm not one of them, but do believe in minimizing the number of returns as much as possible without making the code ugly in doing it.
digitaljoel
Yeah, it's definitely not something to overuse, but sometimes it just makes it a lot easier and can still be very readable.
CookieOfFortune
+7  A: 

You can have return in a void method, you just can return anything. 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
}
Pesto
+4  A: 

The Java language specification says you can have return with no expression if your method returns void.

John Ellinwood
+1  A: 

It functions the same as a return for function with a specified parameter, except it returns nothing, as there is nothing to return and control is passed back to the calling method.

Chris Ballance
+1  A: 

It exits the function and returns nothing.

Something like return 1; would be incorrect since it returns integer 1.

Albert
A: 

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

MahdeTo