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.
See this example, you want to add to the list conditionally. Without the word "return", all ifs will be executed and add to the ArrayList!
Arraylist<String> list = new ArrayList<>();
public void addingToTheList() {
if(isSunday()) {
list.add("Pray today")
return;
}
if(isMonday()) {
list.add("Work today"
return;
}
if(isTuesday()) {
list.add("Tr today")
return;
}
}
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.
The Java language specification says you can have return with no expression if your method returns void.
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.
It exits the function and returns nothing.
Something like return 1;
would be incorrect since it returns integer 1.
Source: Stackoverflow.com