wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Return statement necessity 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 "Return statement necessity" Watch "Return statement necessity" New topic
Author

Return statement necessity

Aniket Patil
Ranch Hand

Joined: May 02, 2006
Posts: 218
According to JLS, it is possible for a method to have a declared return type and yet contain no return statements.

Example:
class DizzyDean {
int pitch() { throw new RuntimeException("90 mph?!"); }
}

Why does this not work?

class ConstantAccess
{
int method()
{
System.out.println("Inside method()");

}

}


SCJP 5.0 | SCWCD 1.4 <br /> <br />If you don't know where you are going, any road will take you there!
Ivan Rebrov
Ranch Hand

Joined: Jul 09, 2006
Posts: 30
Originally posted by Aniket Patil:
According to JLS, it is possible for a method to have a declared return type and yet contain no return statements.

Example:
class DizzyDean {
int pitch() { throw new RuntimeException("90 mph?!"); }
}

Why does this not work?

class ConstantAccess
{
int method()
{
System.out.println("Inside method()");

}

}


I think that's a wrong point of view. It is better do say so:

If method has a declared return type it must contain return statement.

BUT (!) there are some exceptions: for example, if the code after some statement becomes unreachable (for. ex. after not checked "throw" ).

And this exception is absolutely logical, if you insert "return" statement after "throw" in your example compiler should tell you "Unreachable code".
[ August 16, 2006: Message edited by: Ivan Rebrov ]

SCJP 5.0 - 95%<br />Preparing for SCWCD
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
According to JLS, it is possible for a method to have a declared return type and yet contain no return statements.

Which section of which version of the JLS?
[ August 16, 2006: 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.
Aniket Patil
Ranch Hand

Joined: May 02, 2006
Posts: 218
The Java Language Specification 3.0, Section 8.4.8, Pg. 224, right at the top of the page.

I got the idea from Ivan's reply. If the return statment becomes unreachable, it can be omitted. This is what the JLS was trying to say.
[ August 16, 2006: Message edited by: Aniket Patil ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Return statement necessity