Java Reference
In-Depth Information
Recall that a method is a set of instructions used to manipulate values,
generate outputs, or perform actions. Methods have a unique name that usually
includes an active verb, such as get or write, followed by a descriptive word such
as Tax or Output. As with Java-defined methods, any method you write must
follow certain syntax rules.
Creating a method is a two-part process that involves writing a call state-
ment and then writing the code for the method itself.
Calling a Method
When you reach the place in the program where the method is to perform
its service, you must write code to call the method. The call is a line of code stat-
ing the name of the method, followed by any data needed by the method in the
form of arguments enclosed in parentheses. Once the method performs its serv-
ice, it may return a value, or an answer, to the program.
Table 4-3 shows the general form of the statements used to call a method.
Table 4-3
Method Call
General form:
1.
callMethod(argument); //with one argument
2.
callMethod(argument1, argument2); //arguments separated by commas
3.
callMethod(); //no arguments
4.
firstMethod(secondMethod()); //method used as argument
5.
returnValue = callMethod(argument); //method returns a value
Purpose:
To transfer execution of the program to another method
Examples:
1. displayOutput(answer);
2. getCommission(sales, rate);
3. finish();
4. System.out.println(output());
5. salesTax = getTax(sales);
In example 1, a method is called and set with one argument, which is
enclosed within parentheses. When sending multiple arguments, as in example 2,
the arguments are separated by commas. If you have no arguments, as shown in
example 3, you still must include the parentheses with nothing inside. As shown
in example 4, the method call also can be part of another method or statement.
In example 4, the output() method is the argument of the println() method.
In program code, it is quite common to call a method that performs a func-
tion designed to return an answer. In that case, the method call becomes part of
an assignment statement, as shown in example 5. Example 5 calls a method
named getTax(), sends an argument named sales, and receives a return value that
the program stores in the variable location named salesTax.
Line 22 in Figure 4-8 shows the line of code that calls the getSales() method
in the Commission program. When the method is called, no arguments are sent,
but the method returns a value that the program stores in the variable location
named dollars.
 
Search WWH ::




Custom Search