I\'m looking at a path finding tutorial and I noticed a return
statement inside a void
method (class PathTest
, line 126):
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
}
The keyword simply pops a frame from the call stack returning the control to the line following the function call.
The Java language specification says you can have return with no expression if your method returns void.
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.
It exits the function and returns nothing.
Something like return 1;
would be incorrect since it returns integer 1.