Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does return mean at the end of a void method?

Tags:

java

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?

like image 506
Saravanan Avatar asked Sep 14 '11 06:09

Saravanan


People also ask

What does return in void method mean?

Your return statement has no argument, so it is not returning anything, hence the returned value is 'void'. Follow this answer to receive notifications.

Can a void have a return?

Void functions do not have a return type, but they can do return values.

Do you need a return at the end of a void function?

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.


2 Answers

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:

  • Terminating execution of the current method (via finally blocks of course)
  • Making a value computed in the method available to the caller

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.

like image 186
Jon Skeet Avatar answered Nov 10 '22 07:11

Jon Skeet


Your return statement has no argument, so it is not returning anything, hence the returned value is 'void'.

like image 22
loganfsmyth Avatar answered Nov 10 '22 07:11

loganfsmyth