1

I am well aware that the void keyword is used to indicate in a method declaration that the method will return no value. My question is not about - to use an analogy - how to use the car, but rather about what's underneath the hood. I would like to know why void actually needs to be specified, i.e. does Java reserve an internal variable of some sort to keep track of return types? Will setting a method to void make it so that it doesn't have to do this?

Another way to put it is to ask why, exactly, can't Java omit the void keyword and assume that if there is no returned type than the method is void? I think that there is something to do with how Java might "prepare" to handle the return type, and possibly something to do with optimization... please use full detail.

  • 1
    Possible duplicate of http://stackoverflow.com/questions/7367381/what-does-void-do-in-java – Elliott Frisch Dec 11 '13 at 07:43
  • 1
    If you'd omit void, it'd be a constructor, it is simply a way to keep the syntax and parser simple: all methods have a return type, even if they don't return anything. – Mark Rotteveel Dec 11 '13 at 07:45
  • If you want to see whats under the hood, you can just look at the source code. As for why methods have return types, Mark is correct. – Rahul Iyer Dec 11 '13 at 07:50
  • its just syntax.and yes, clear syntax helps compilers to do things easily and without ambiguation. – qwr Dec 11 '13 at 07:51
  • possible duplicate of [What does a return key word do in a void method in Java?](http://stackoverflow.com/questions/744676/what-does-a-return-key-word-do-in-a-void-method-in-java) – Vorsprung Dec 11 '13 at 08:16
  • If somebody could please tell me how my question introduces a bias, I would be able to fix it. At the moment, just putting it on hold isn't good enough. I have no idea how my question can be construed as opinionated. –  Dec 11 '13 at 08:22

2 Answers2

2

Its a java language Specification void used with only methods declaration

if we omit void then its treated as constructor.

SEE THIS

KhAn SaAb
  • 5,007
  • 5
  • 26
  • 48
  • My God, this solved a lot of pain I was having. I can now use super and I now understand why super only works when you omit void from the constructor and why it works being omitted. – Joseph Kreifels II Jun 01 '16 at 16:11
1

my answer is a bit of a guess. But I'd say its to protect the developer against just forgetting to declare the return type. Sure the compiler can even by default be programmed to render undeclared return types void. But that would be at cost to the aid for the developer.

Furthermore, IDEs would have to anticipate on the same.

nl-x
  • 11,109
  • 6
  • 28
  • 53