File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Constructors can Return Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Constructors can Return" Watch "Constructors can Return" New topic

Constructors can Return

Sandeep Chhabra
Ranch Hand

Joined: Aug 28, 2005
Posts: 340
An abstract from Khalid A. Mughal book for SCJP 1.4 says
Constructors cannot return a value and, hence, cannot specify a return type, not even void, in the constructor header, but they can contain the simple form of the return statement in the constructor body.


would compile and run and print Constructor.
But i dont understand why would we ever need to use empty return statement in a constructor when actually it cannot return anything?


Regards<br />Sandy<br />[SCJP 5.0 - 75%]<br />[SCWCD 1.4 - 85%]<br />------------------<br />Tiger, Tiger burning bright,<br />Like a geek who works all night,<br />What new-fangled bit or byte,<br />Could ease the hacker's weary plight?
Joseph Clark
Ranch Hand

Joined: Sep 10, 2005
Posts: 48
The only reason I can think of would be to return out of some kind of conditional construct.

if(some condition){
//do something
else if (something other condition){
//do something else
Anupam Sinha
Ranch Hand

Joined: Apr 13, 2003
Posts: 1090
Hi Sandeep

Maybe it is useful in loops or some if test.

Example :
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
As Michael wrote, you may want to quickly get out of the constructor for some reason. You would still have an instance of the object being constructed, but it would possibly be only partially initialised.

This early return technique is also useful in any method returning void.
[ September 11, 2005: Message edited by: Barry Gaunt ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
I agree. Here's the link:
subject: Constructors can Return
jQuery in Action, 3rd edition