The method-body of a method declaration consists either of a block or a semicolon.
Abstract and external method declarations do not provide a method implementation, and the method body of an abstract or external method simply consists of a semicolon. For all other methods, the method body is a block (§8.2) that contains the statements to execute when the method is invoked.
When the return type of a method is void
, return
statements (§8.9.4) in the method body are not permitted to specify an expression. If execution of the method body of a void method completes normally (that is, if control flows off the end of the method body), the method simply returns to the caller.
When the return type of a method is not void
, each return
statement in the method body must specify an expression of a type that is implicitly convertible to the return type. Execution of the method body of a value-returning method is required to terminate in a return
statement that specifies an expression or in a throw
statement that throws an exception. It is an error if execution of the method body can complete normally. In other words, in a value-returning method, control is not permitted to flow off the end of the method body.
In the example
class A { public int F() {} // Error, return value required public int G() { return 1; } public int H(bool b) { if (b) { return 1; } else { return 0; } } }
the value-returning F
method is in error because control can flow off the end of the method body. The G
and H
methods are correct because all possible execution paths end in a return statement that specifies a return value.