user2097804
user2097804

Reputation: 1132

return void in a void method?

I know I can do this:

void someMethod(){
 return;
 }

but I get a syntax error on

void someMethod(){
return void;
}

Why is the latter not allowed? It makes more sense to me.

Edit: I know what a void method is, and that I don't have to return from it at all(and probably shouldn't, in most cases) but I don't understand why I can't return void from a void method. In my opinion, there should be no keyword in the method declaration (like constructors) if the you are able to write return;.

Upvotes: 0

Views: 3300

Answers (5)

Mike Samuel
Mike Samuel

Reputation: 120586

return x; indicates that control is leaving the method and that its result is the value of x.

return; indicates that control is leaving the method without a result.

The type void is a type with zero values, so for void methods there is no x such that return x makes sense.

All non-void methods must do one of three things:

  1. Fail to exit ever.
  2. Finish abnormally with an exception.
  3. Finish normally with zero or one return values.

Since void is the only type with zero possible values (Classes with private uncalled ctors don't count because of null), there is no possible return in a non-void method such that return makes sense.

Upvotes: 1

Sebastian Redl
Sebastian Redl

Reputation: 72215

void is a type, not an expression, so trying to write return void is the same as trying to write return int: syntactically invalid.

Upvotes: 2

user195488
user195488

Reputation:

When you call return void;, you are using a reserved keyword in the incorrect manner. Since it would not expect the keyword void in that manner, it would cause an error.

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

If you would prefer to return something, then you can return null; by parameterizing a type Void like in this answer, but that's unconventional. Best bet is to omit return altogether or just say return;.

Upvotes: 1

When you declare a method as void, you're saying that the method does not return a value. Attempting to return a value, therefore, is illegal. Additionally, return void; has a syntax error because void is not (indeed, cannot be) the name of an in-scope variable.

Upvotes: 2

duffymo
duffymo

Reputation: 309008

I think both are to be shunned. I prefer this:

void someMethod() {
    // do stuff; no return at bottom
}

I'd be willing to be that you'd find lots of methods in the JDK source code that look like this.

Upvotes: 6

Related Questions