Java Reference
In-Depth Information
Passing an Array as a Parameter
You can pass an array as a parameter to a method or a constructor. The type of array you pass to the method must be
assignment compatible to the formal parameter type. The syntax for an array type parameter declaration for a method
is the same as for the other data types. That is, parameter declaration should start with the array type, followed by one
or more whitespaces and the argument name, as shown:
modifiers returnType methodName(ArrayType argumentName, ...)
The following are some examples of method declarations with array arguments:
// The processSalary() method has two parameters:
// 1. id is an array of int
// 2. salary is an array of double
public static void processSalary(int[] id, double[] salary) {
// Code goes here...
}
// The setAKA() method has two parameters:
// 1. id is int (It is simply int type, not array of int)
// 2. aka is an array of String
public static void setAKA(int id, String[] aka) {
// Code goes here...
}
// The printStates() metohd has one parameter:
// 1. stateNames is an array of String
public static void printStates(String[] stateNames) {
// Code goes here...
}
The following code fragment for a method mimics the toString() method of ArrayList . It accepts an int array
and returns the comma-separated values enclosed in brackets ( [] ).
public static String arrayToString(int[] source) {
if (source == null) {
return null;
}
// Use StringBuilder to improve performance
StringBuilder result = new StringBuilder("[");
for (int i = 0; i < source.length; i++) {
if (i == source.length - 1) {
result.append(source[i]);
}
else {
result.append(source[i] + ",");
}
}
result.append("]");
return result.toString();
}
 
Search WWH ::




Custom Search