Java Reference
In-Depth Information
table[1].length will return 2 because there are two elements in the second row of the
table (remember that index counting for arrays starts at 0).
Note that Java supports arrays of any number of dimensions. For example, a three-
dimensional array of integer can be defined as follows.
int [][][] table;
Of course, this three-dimensional array is stored in Java as an array of two-dimensional
arrays. As we explained earlier, a two-dimensional array is represented, in turn, as an array
of arrays.
5.4 Variable Argument Methods
Java allows us to write a method that takes as input a variable number of arguments.
You have seen the printf method, which can take as input any number or parameters.
Such a method is written using an array. For example, consider a method that takes as
input a variable number of strings and returns the result of concatenating the strings. It
can be implemented as shown below.
public static String concat(String ... strings) {
String result = "" ;
for (String s: strings)
result += s;
return result ;
Note that the declaration String ... strings denotes that the method takes as input
a variable number of strings. Theses strings are processed in the method as an array of
strings. For example, suppose that the method is called as follows.
System. out . println ( concat ( "cat" , "dog" , "fight));
Java will create the string array:
and pass it as input to the
concat method. In order for this to work in unambiguous fashion, it must be the case
that the variable number of arguments is always the last parameter of the method. For the
example, the return value will be the string "catdogfight" . Note that the operator “+=”
means use the string on the left and append the string on the right to it.
An array can also be passed as a parameter to a method that takes as input a variable
number of arguments. The following code will also print catdogfight .
System. out . println ( concat ( new String []
{ "cat","dog","fight" }
{ "cat" , "dog" , "fight}));
Lastly, note that a variable number of arguments includes sending no parameters to the
method. For example, the following code will just print a new line.
Search WWH ::

Custom Search