Java Reference
In-Depth Information
public static int getAverage(int[] intArray)
parameter list
method name
return type
modifier
access specifier
Figure 12-1 Elements of a Method Declaration
Access specifier
The method's access specifier is optional. The access specifier controls ac-
cess to the method. The access specifiers are public , protected, and pri-
vate . Public is the least restrictive one. Access specifiers for methods are
discussedinthecontextofobject-orientedprogrammingin Chapter14 .
Modifier
The modifier sets the properties for the method. The value for the modifier
are static , abstract , final , native , and synchronized . Modifiers are related
to the method's visibility and the method's attributes within the class struc-
ture.
You can also create methods that are unrelated to objects by using the
static modifier. This is the case with the getAverage() method listed previ-
ously and with the main() method that you have been using in your pro-
grams.
Return type
The return type is a required element in the method declaraction. The one
exception is a special type of methods, called constructors, which are dis-
cussedin Chapter15 .Allmethodscanreturnasinglevaluetothecaller.The
return type identifies the data type of the returned value. Java methods can
return any of the eight primitive data types ( int, long, short, byte, boolean,
float, and double, and char) or more complex types, such as arrays and ob-
jects. Since a string is an object of the String class, a Java method can return
a string object to the caller. When a method returns no value, its return type
is declared to be void. If the method's return type is not void, it must return
the type specified in the declaration.
The following method returns a type boolean:
public static boolean isOdd(int aValue)
{
 
Search WWH ::




Custom Search