Method Declarations – Declarations

3.2 Method Declarations

A method declaration has the following syntax:

Click here to view code image

method_modifiers return_type method_name
             (
formal_parameter_list
)
throws_clause
 // Method header
{ // Method body
local_variable_declarations
statements
}

In addition to the name of the method, the method header can specify the following information:

  • The following method modifiers:

Image Access modifiers: public, protected, private (§6.5, p. 347)

Image Non-access method modifiers: static (p. 115), abstract (§5.4, p. 224), final (§5.5, p. 226), synchronized (§22.4, p. 1388)

  • The type of the return value, or void if the method does not return any value

A non-void method must either use a return statement (§4.13, p. 184) to return a value or throw an exception to terminate its execution.

  • A formal parameter list

The formal parameter list is a comma-separated list of parameters for passing information to the method when the method is invoked by a method call (p. 127). An empty parameter list must be specified by ( ). Each parameter is a simple variable declaration consisting of its type and name:

optional_parameter_modifier type parameter_name

The parameter names are local to the method (§6.6, p. 354). The optional parameter modifier final is discussed in §3.10, p. 135. It is recommended to use the @param tag in a Javadoc comment to document the formal parameters of a method.

The type in the parameter declaration cannot be designated by the var reserved type name, as illustrated in the method declaration below. At compile time, it is not possible to determine the type of the newSpeed formal parameter.

Click here to view code image

void setSpeed(var newSpeed) {} // var not permitted. Compile-time error!

  • Any exceptions thrown by the method, which are specified in a throws clause (§7.5, p. 388)

The method body is a block ({}) containing the local variable declarations (p. 102) and the statements (p. 101) of the method. The return statement in the body of a method is of particular importance as it terminates the execution of the method and can optionally return a value to the caller of the method (§4.13, p. 184).

The mandatory parts of a method declaration are the return type, the method name, and the method body curly brackets ({}), as exemplified by the following method declaration:

void noAction() {}

Member methods are characterized as one of two types: instance methods (p. 106) and static methods (p. 112).

The signature of a method comprises the name of the method and the types of the formal parameters only. The following method:

Click here to view code image

double cubeVolume(double length, double width, double height) {}

has the signature:

Click here to view code image

cubeVolume(double, double, double)