Java Reference
In-Depth Information
Method with a Variable Number of Parameters
A method with a variable number of parameters has a vararg specification as the last item
on its parameter list. A vararg specification has the following form:
Type ... Array_Name
Some examples of vararg specifications are
int ... arg
double ... a
String... unwanted
Displays 6.7 and 6.8 show two of these vararg specifications in complete method definitions.
In any invocation of a method with a vararg specification, you handle arguments corresponding
to regular parameters in the usual way. Following the arguments for regular parameters, you
can have any number of arguments of the type given in the vararg specification. These
arguments are automatically placed in an array, and the array can be used in the method
definition. A full description of the details is given in this chapter.
Self-Test Exercises
16. Redo the defi nition of the method max in Display 6.7 using a for-each loop in
place of the regular for loop.
17. What would be the dialogue in Display 6.8 if we omit the following line from
the program?
sentence = Utility2.censor(sentence, " ,"); //Deletes extra commas
EXAMPLE: A String Processing Example
This example uses material from the earlier starred subsection “Methods with a
Variable Number of Parameters.” If you have not read that subsection, you should
skip this example.
Display 6.8 contains a utility class with the string processing method named
censor and an example of a program that uses that method. The method censor
takes a single String parameter followed by any number of additional parameters
of type String . The first parameter will be a sentence or other string that may
contain substrings you want to delete. The method returns its first parameter with all
occurrences of the remaining string parameters removed.
(continued)
 
Search WWH ::




Custom Search