4.13. Programming Exercises

 
[Page 130 ( continued )]

5.2. Creating a Method

In general, a method has the following syntax:

 modifier returnValueType methodName(list of parameters) {  // Method body;  } 

Let's take a look at a method created to find which of two integers is bigger. This method, named max , has two int parameters, num1 and num2 , the larger of which is returned by the method. Figure 5.1 illustrates the components of this method.

Figure 5.1. A method declaration consists of a method header and a method body.

The method header specifies the modifiers , return value type , method name , and parameters of the method. The modifier, which is optional, tells the compiler how to call the method. The static modifier is used for all the methods in this chapter. The reason for using it will be discussed in Chapter 7, "Objects and Classes."

A method may return a value. The returnValueType is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void . For example, the returnValueType in the main method is void , as well as in System.exit , System.out.println , and JOptionPane.showMessageDialog . The method that returns a value is called a nonvoid method , and the method that does not return a value is called a void method .

The variables defined in the method header are known as formal parameters or simply parameters . A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument . The parameter list refers to the type, order, and number of the parameters of a method. The method name and the parameter list together constitute the method signature . Parameters are optional; that is, a method may contain no parameters.


[Page 131]

The method body contains a collection of statements that define what the method does. The method body of the max method uses an if statement to determine which number is larger and return the value of that number. A return statement using the keyword return is required for a nonvoid method to return a result. The method terminates when a return statement is executed.

Note

In certain other languages, methods are referred to as procedures and functions . A method with a nonvoid return value type is called a function ; a method with a void return value type is called a procedure .


Caution

You need to declare a separate data type for each parameter. For instance, int num1 , num2 should be replaced by int num1 , int num2 .


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net