next up previous
Next: Example: use of static Up: Unit 03 Previous: Examples of definitions of

Result of a method: the return statement

If a method must return a result, then it must contain a return statement.

When the return statement is executed inside a method it causes the termination of the method and it returns its result to the client module (i.e., the part of the program where the method was called).

The syntax of the return statement is as follow:

return expression;

where expression must be an expression whose value is compatible with the type of the result declared in the method header.

Example:

public static String personalGreeting(String firstName, String lastName) {
  return "Good morning " + firstName + " " + lastName + "!";
}

If the result type is void, the return statement can be omitted, or it can simply be used to interrupt the execution of the method. Since in this case it is not necessary to return a result, the syntax in this case is as follows:

return;

Note: The execution of the return statement always terminates the method, even if there are additional instructions that follow.


next up previous
Next: Example: use of static Up: Unit 03 Previous: Examples of definitions of