I know that there are times when using return;
can serve a useful purpose in Java, such as in guarding:
public void foo(Bar bar) {
if(bar == null)
return;
// bar is not null, go ahead and do stuff with it
}
But what about just reaching the end of a method with return type void
? For example,
public void printMenu() {
System.out.println("Print out some boilerplate info here, line 1.");
System.out.println("Print out some boilerplate info here, line 2.");
System.out.println("Print out some boilerplate info here, line 3.");
return;
}
Other than pure style preferences, are there any reasons for or against including that return;
? If so, what are they?
EDIT: Well, that got answered quickly. To summarize the 15 answers posted below: "No."
A function that does not return a value is called a non-value returning function (or a void function). A void function will automatically return to the caller at the end of the function. No return statement is required.
A return statement is used to exit from a method, with or without a value. For methods that define a return type, the return statement must be immediately followed by a return value. For methods that don't return a value, the return statement can be used without a return value to exit a method.
A void return type simply means nothing is returned. System. out. println does not return anything as it simply prints out the string passed to it as a parameter.
When a return statement contains an expression in functions that have a void return type, the compiler generates a warning, and the expression isn't evaluated.
Perhaps you're paid by line of code?
Other then that there's really no reason to put an empty return in the end.
I avoid them, myself. It's just a useless line of code. In fact, PMD has a rule that checks for such useless return
statements.
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