Help coderanch get a
new server
by contributing to the fundraiser
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

Can a Constructor Body have a return statement?

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class ConsTest{
public ConsTest(){
int i=0;
int j=3;
return;
}
public static void main(String args[]){ConsTest t=new ConsTest();}
}
This compiles and runs perfectly
Java specifications says that a constructor body can have
a return statement but the return statement should not
have a expression
Can anybody explain then what is the purpose of
a return statement at all in a constructor body
 
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The return statement here is used to "stop" execution of the code, just the way you do it in a void method. Sometimes such a strategy will help you to exit from deeply nested control structures, a nested-if block which has, lets say 3 levels of nesting.
Ajith
reply
    Bookmark Topic Watch Topic
  • New Topic