I know that a void
method does not return any value, but I can still write code like
void nothingDohere() {return;}
So, How can "void" work with the "return" statement here?
Your return statement has no argument, so it is not returning anything, hence the returned value is 'void'. Follow this answer to receive notifications.
Void functions do not have a return type, but they can do return values.
In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value. You may or may not use the return statement, as there is no return value.
A return statement without a value can only be used in a void
method (or a constructor), and simply performs the "get out of the method now" part of returning. Think of a return-with-value statement has having two purposes:
finally
blocks of course)The return statement in a void
method simply achieves the first of these; the second makes no sense in a void
method.
From section 14.17 of the Java Language Specification:
A return statement with no Expression must be contained in the body of a method that is declared, using the keyword void, not to return any value (§8.4), or in the body of a constructor (§8.8). A compile-time error occurs if a return statement appears within an instance initializer or a static initializer (§8.7). A return statement with no Expression attempts to transfer control to the invoker of the method or constructor that contains it. To be precise, a return statement with no Expression always completes abruptly, the reason being a return with no value.
Your return statement has no argument, so it is not returning anything, hence the returned value is 'void'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With