8.4 Method Declarations

The diversity of physical arguments and opinions embraces all sorts of methods.
—Michael de Montaigne (1533-1592), Of Experience

A method declares executable code that can be invoked, passing a fixed number of values as arguments.

MethodDeclaration:
MethodHeader MethodBody
MethodHeader:
MethodModifiersopt ResultType MethodDeclarator Throwsopt
ResultType:
Type
void
MethodDeclarator:
Identifer ( FormalParameterListopt )

The MethodModifiers are described in §8.4.3, the Throws clause in §8.4.4, and the MethodBody in §8.4.5. A method declaration either specifies the type of value that the method returns or uses the keyword void to indicate that the method does not return a value.

The Identifier in a MethodDeclarator may be used in a name to refer to the method. A class can declare a method with the same name as the class or a field of the class.

For compatibility with older versions of Java, a declaration form for a method that returns an array is allowed to place (some or all of) the empty bracket pairs that form the declaration of the array type after the parameter list. This is supported by the obsolescent production:

MethodDeclarator:
MethodDeclarator [ ]

but should not be used in new Java code.

It is a compile-time error for the body of a class to have as members two methods with the same signature (§8.4.2) (name, number of parameters, and types of any parameters). Methods and fields may have the same name, since they are used in different contexts and are disambiguated by the different lookup procedures (§6.5).