What does the return keyword do in a void method in Java?
Solution 1:
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
}
Solution 2:
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
}
Solution 3:
The keyword simply pops a frame from the call stack returning the control to the line following the function call.
Solution 4:
The Java language specification says you can have return with no expression if your method returns void.
Solution 5:
It exits the function and returns nothing.
Something like return 1;
would be incorrect since it returns integer 1.