double
(2.2) to
int
, which is the type
of
nums
in
MinVal( )
.
When using
params
, you need to be careful about boundary conditions because a
params
parameter can accept any number of arguments—
even zero!
For example, it is
syntactically valid to call
MinVal( )
as shown here:
min = ob.MinVal(); // no arguments
min = ob.MinVal(3); // 1 argument
This is why there is a check in
MinVal( )
to confirm that at least one element is in the
nums
array before there is an attempt to access that element. If the check were not there, then a
runtime exception would result if
MinVal( )
were called with no arguments. (Exceptions are
described in Chapter 13.) Furthermore, the code in
MinVal( )
was written in such a way as to
permit calling
MinVal( )
with one argument. In that situation, the lone argument is returned.
A method can have normal parameters and a variable-length parameter. For example,
in the following program, the method
Do'stlaringiz bilan baham: |