File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Return statement necessity

 
Aniket Patil
Ranch Hand
Posts: 218
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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()");

}

}
 
Ivan Rebrov
Ranch Hand
Posts: 30
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Aniket Patil
Ranch Hand
Posts: 218
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic