A method returns to the code that invoked it when it
- completes all the statements in the method,
- reaches a
return
statement, or - throws an exception,
whichever occurs first.
You declare a method's return type in its method declaration. Within the body of the method, you use the return
statement to return the value.
Any method declared void
doesn't return a value. It does not need to contain a return
statement, but it may do so. In such a case, a return
statement can be used to branch out of a control flow block and exit the method and is simply used like this:
return;
If you try to return a value from a method that is declared void
, you will get a compiler error.
Any method that is not declared void
must contain a return
statement with a corresponding return value, like this:
return returnValue;
The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean.
_______________________________________________________________________________________________________________________
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 }