Method
A method is a block of statements that has a name and can be executed by calling (also called invoking) it from some other place in your program. Along with fields, methods are one of the two elements that are considered members of a class. (Constructors and initializers are not considered class members.)
Every program must have at least one method for the program to accomplish any work. And every program must have a method named main
, which is the method first invoked when the program is run.
All methods — including the main
method — must begin with a method declaration. Here’s the basic form of a method declaration, at least for the types of methods I talk about in this chapter:
visibility [static] return-type method-name (parameter-list)
{
statements...
}
The following list describes the method declaration piece by piece:
visibility
: The visibility of a method determines whether the method is available to other classes. The options are
• public
: Allows any other class to access the method
• private
: Hides the method from other classes
• protected
: Lets subclasses use the method but hides the method from other classes
static
: This optional keyword declares that the method is a static method, which means that you can call it without first creating an instance of the class in which it’s defined. The main
method must always be static, and any other methods in the class that contains the main
method usually should be static as well.
return-type
: After static
comes the return type, which indicates whether the method returns a value when it is called — and if so, what type the value is. If the method doesn’t return a value, specify void
.
If you specify a return type other than void
, the method must end with a return
statement that returns a value of the correct type. For more information, see return Statement.
method-name
: Now comes the name of your method. The rules for making up method names are the same as the rules for creating other identifiers: Use any combination of letters and numbers, but start with a letter.
parameter list
: You can pass one or more values to a method by listing the values in parentheses following the method name. The parameter list in the method declaration lets Java know what types of parameters a method should expect to receive and provides names so that the statements in the method’s body can access the parameters as local variables.
statements
: One or more Java statements that comprise the method body, enclosed in a set of braces. Unlike Java statements such as if
, while
, and for
, the method body requires you to use the braces even if the body consists of only one statement.