Java Reference
In-Depth Information
The Method Header
The first line of code inside the Welcome class is the main() method header.
As discussed in Chapter 1, a method is the code to perform a service or opera-
tion, including manipulating values, generating outputs, or performing actions.
Methods are the basic building blocks in Java code and thus are very important.
Where other programming languages have functions, Java has methods.
To code a method in Java, you begin with a method header. The method
header notifies the Java compiler of the method's attributes, the type of data it
will generate (if any), the name of the method, and any other information or
parameters the method needs to perform a service or operation. Table 2-5 shows
the general form of a method header.
Table 2-5
Method Header
modifier returnDataType methodName(DataType parameter)
{
General form:
//code to execute when the method is called
}
To notify the compiler of a method, its attributes, the type of
data it will return (if any), and to provide a list of parameters
the method may need. A method header can have several access
modifiers and several parameters, or it can have none. Any
parameters follow the method name in parentheses, with each
parameter preceded by its data type. Multiple parameters are
separated by commas. A method header can have only one
return data type.
Purpose:
1. public static void main(String[] args)
2. public void paint(Graphics g)
3. public void init( )
4. public double getOvertime(double hours, double
rate)
Examples:
Every stand-alone Java application must contain a main () method , which is
the starting point during execution. The code in the main() method is performed
sequentially during execution; however, the main() method may call other meth-
ods in the program. The main() method starts with the main() method header, as
shown in line 12 of the Welcome to My Day program (Figure 2-21).
12
public
static
void main ( String []
args )
13
{
14
FIGURE 2-21
A method header usually begins with one or more method modifiers. A
method modifier is used to set properties for the method. In line 12, the access
modifier, public, declares the method's visibility just as it did when used as an
access modifier for a class. Because the main() method is public, other programs
 
Search WWH ::




Custom Search