• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why return statement is valid in java constructor ?  RSS feed

 
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Constructors do not have return type.then why there is no restriction when we write return in constructor.
 
Ranch Hand
Posts: 633
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In constructor you can only write return to stop execution. You can't write return with some value.
 
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
'return' in this case means 'leave' or 'finished processing'
It is more like a machine code 'return subroutine' instruction
 
Satyajit Bhadange
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry but i am not comfortable with an explanation.

It doesnt make sense to write return in constructor but we can still write it..Why java does not give any compiler error.
 
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The return keyword doesn't really mean "here is the value I want to return to you". It actually means "I've gotten this far in the current routine, but now I want to return to the calling routine".

Methods with a return type *have* to pass a value back to the calling routine, so when the method ends abruptly through the return keyword, you also specify a value to return. But actually all that return means is "stop the method now".
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, there's not much more to explain about it than what David and Pramod already said.

return just means: we're done, go back to the point where the constructor was called. You can use return in exactly the same way in void methods:

There's really nothing special about it. Why is this so hard to accept?
 
Satyajit Bhadange
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok..iget it now..thank you..
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!