Sub topic 7
Passing and Returning Arrays
A Java method can receive an array, use its elements, and return an array. This lets you put work in one place instead of writing it again each time you need it.
This chapter assumes you have created arrays and used loops to visit their elements. We will focus on what happens to an array when a method receives or returns it.
Arrays as method inputs
A method is a named set of instructions. A method can have a parameter, which is a variable that receives an input. An argument is the value supplied when the method is called.
For example, in addFiveToFirst(scores), scores supplies the argument. The method receives that value in its parameter, values.
An array variable holds a reference: a value that identifies an array object. The array object holds the elements. When you pass an array to a method, Java gives the method a copy of the reference, not a copy of the array.
The caller’s variable and the method’s parameter can therefore refer to the same array.
Changing an array in a method
A method can change elements of an array it receives. Because the caller still refers to the same array, the caller can see those changes.
Save this program as PassingArrays.java:
public class PassingArrays {
static void addFiveToFirst(int[] values) {
if (values.length > 0) {
values[0] = values[0] + 5;
}
}
static void replaceLocally(int[] values) {
values = new int[] {10, 20};
values[0] = 99;
}
public static void main(String[] args) {
int[] scores = {80, 90, 100};
addFiveToFirst(scores);
System.out.println(scores[0]); // 85
replaceLocally(scores);
System.out.println(scores[0]); // 85
}
}Compile and run it from the folder containing the file:
javac PassingArrays.java
java PassingArraysThe program prints 85 twice.
The first method call works like this:
scoresrefers to the array containing80,90, and100.- The
valuesparameter receives a copy of that reference. values[0] = values[0] + 5changes the first element of the shared array.- When the method finishes,
scores[0]is85.
The check values.length > 0 matters. An empty array has no first element, so accessing values[0] would cause an error.
The word void means the method does not return a value. It can still change an array. The word static lets these methods be called from main without first creating an object of the class.
Changing an element is not the same as changing a parameter
The second method, replaceLocally, does something different:
values = new int[] {10, 20};This statement creates another array and makes the local values parameter refer to it. A local variable is a variable used within a method. Changing it does not change the caller’s scores variable.
The next statement changes the first element of the new array to 99. It does not change the original array. When the method finishes, scores still refers to the original array, whose first element is 85.
Returning a new array
A return value is the result a method gives back to its caller. To return an array of integers, put int[] before the method name. Inside the method, use return followed by the array reference.
The next program creates an array containing a counting sequence. It also shows the difference between returning a new array and returning an array that already exists.
Save it as ReturnArrays.java:
public class ReturnArrays {
static int[] makeSequence(int size) {
if (size < 0) {
throw new IllegalArgumentException("size must be 0 or more");
}
int[] result = new int[size];
for (int i = 0; i < result.length; i++) {
result[i] = i + 1;
}
return result;
}
static int[] share(int[] values) {
return values;
}
public static void main(String[] args) {
int[] first = makeSequence(3);
int[] second = makeSequence(3);
int[] shared = share(first);
shared[0] = 99;
System.out.println(first[0]); // 99
System.out.println(second[0]); // 1
int[] empty = makeSequence(0);
System.out.println(empty.length); // 0
}
}Compile and run it:
javac ReturnArrays.java
java ReturnArraysThe output is 99, 1, and 0, each on its own line.
Following the new array
The call makeSequence(3) creates an array of length three. The loop fills it with 1, 2, and 3. The return statement sends the reference back to the caller, where it is stored in first.
The local variable result is no longer available after the method finishes. The array is still available through first.
The second call to makeSequence(3) creates a separate array. It has the same starting values as the first array, but changing one array does not change the other.
A size of zero is allowed. The method returns an empty array, and the loop has no elements to fill.
A negative size is not allowed. The method throws an exception, which is a signal that something went wrong. Here, IllegalArgumentException tells the caller that the supplied size is not valid.
Following the shared array
The share method does not create an array. It returns the reference it received.
After int[] shared = share(first), both shared and first refer to the same array. Therefore, changing shared[0] also changes the value seen through first[0].
Returning an array does not automatically create a new one. To know whether a returned array is new or shared, read the method’s code or its description.
Decide what a method promises
When you write an array method, make its behavior clear to its callers. A contract is the set of promises and requirements for using a method.
For an array parameter, useful questions include:
- Does the method change the supplied array?
- Does it accept an empty array?
- Does it accept
null? - Does it return a new array or a reference to an existing one?
- What happens when an input is invalid?
null is a value that means a reference does not identify an object. It is not the same as an empty array. An empty array exists and has length zero; null has no length.
For example, addFiveToFirst accepts an empty array and leaves it unchanged. Its caller must not pass null, because the method reads values.length. Trying to read the length through null causes an exception.
The share method, by contrast, simply returns its input. If it receives null, it returns null. Its caller must not assume the result identifies an array.
Clear promises help prevent surprises. A method that changes an input can be useful, but callers need to know that their array will change.
Changing what the caller stores
A method cannot replace the caller’s array variable merely by assigning to its parameter. It can, however, return a reference that the caller chooses to store.
For example, after the calls in ReturnArrays, the caller could use:
first = makeSequence(first.length);
The right side creates and returns a new sequence. The assignment then makes first refer to that new array. This assignment happens in the caller, not inside makeSequence.
The shared variable would still refer to the earlier array. Reassigning one reference variable does not reassign other variables.
Check your understanding
Exercise
A method receives an array and sets its first element to 7. The caller still refers to that array. What value does the caller see in the first element?
Show answer
The caller sees 7 because the method changed the same array.
Exercise
A method assigns a newly created array to its array parameter. Does that assignment make the caller’s variable refer to the new array?
Show answer
No. It changes only the method’s local parameter. The caller’s variable keeps its previous reference.
Exercise
A method returns a new empty int array. Is the result the same as null, and what is its length?
Show answer
No. It is an existing array with length 0.