Java Reference
In-Depth Information
The method name must be a valid Java identifier. Conventionally, a Java method starts with a lowercase and
subsequently a word cap is used. For example, getName , setName , getHumanCount , and createHuman are valid method
names. AbCDeFg is also a valid method name; it just doesn't follow standard conventions.
A method may take input values from its caller. A parameter is used to take an input value from the caller.
A parameter consists of two parts: a data type and a variable name. In fact, a method parameter is a variable
declaration. The variables are used to hold the input values that are passed from the method's caller. A comma is
used to separate two parameters of a method. In the above example, the add method declares two parameters, n1
and n2 . Both parameters are of the int data type. When the add method is called, the caller must pass two int values.
The first value passed from the caller is stored in n1 , and the second value passed from the caller is stored in n2 . The
parameters n1 and n2 are also known as formal parameters.
A method is uniquely identified by its signature in a particular context. The signature of a method is the
combination of its name and its parameter's number, types, and order. Modifiers, return types, and parameter names
are not part of the signature. Table 6-1 lists some examples of method declarations and their signatures. Most often,
you will have situations where you need to understand whether two methods have the same signature. It is very
important to understand that the type and order of the method's parameters are part of its signature. For example,
double add(int n1, double d1) and double add(double d1, int n1) have different signatures because the order
of their parameters differs even though the number and types of parameters are the same.
Table 6-1. Examples of Method's Declarations and Their Signatures
Method Declaration
Method Signature
int add(int n1, int n2)
add(int, int)
int add(int n3, int n4)
add(int, int)
public int add(int n1, int n2)
add(int, int)
public int add(int n1, int n2) throws OutofRangeException
add(int, int)
void process(int n)
process(int)
double add(int n1, double d1)
add(int, double)
double add(double d1, int n1)
add(double, int)
the signature of a method uniquely identifies the method within a class. It is not allowed to have more than one
method in a class with the same signature.
Tip
Finally, the code for the method is specified in the method's body, which is enclosed in braces. Executing the
code for a method is also called “calling a method” or “invoking a method.” A method is invoked using its name
with the values for its parameters, if any, within parentheses. To call your add method, you need to use the following
statement:
add(10, 12);
 
 
Search WWH ::




Custom Search