Passing Arrays to Methods and Returning Arrays
When you lend a friend your house key, they don't get a copy of your house; they get a way into the same house. If they rearrange the furniture, you'll see it when you get home. Passing an array to a method works the same way: the method gets a copy of the reference, so it reaches the same array, and any change it makes to the elements is visible to the caller.
The Method Changes the Caller's Array
public class Gst {
static void addGst(int[] items) {
for (int i = 0; i < items.length; i++) {
items[i] = items[i] * 118 / 100;
}
}
public static void main(String[] args) {
int[] prices = {100, 200, 300};
addGst(prices);
System.out.println(prices[0] + " " + prices[1] + " " + prices[2]);
}
}118 236 354How it works
- Line 10 passes
pricestoaddGst. Java copies the reference, not the array. - Inside the method,
itemspoints to the same array asprices. - Line 4 changes the elements through
items, somainsees the new values.
Try it yourself: add items = new int[]{1, 2, 3}; as the first line of addGst. Does main still see the GST prices? Why not?
Returning a New Array
To leave the original untouched, build and return a new array:
public class Discounted {
static int[] withDiscount(int[] prices, int percent) {
int[] result = new int[prices.length];
for (int i = 0; i < prices.length; i++) {
result[i] = prices[i] - prices[i] * percent / 100;
}
return result;
}
public static void main(String[] args) {
int[] prices = {500, 1200, 80};
int[] sale = withDiscount(prices, 10);
System.out.println("Original: " + java.util.Arrays.toString(prices));
System.out.println("Sale: " + java.util.Arrays.toString(sale));
}
}Original: [500, 1200, 80]
Sale: [450, 1080, 72]The return type int[] says the method hands back an array. The caller keeps both versions. Methods themselves are covered fully in "Methods in Java"; this lesson focuses on what happens to the array.
Common Mistakes
Thinking the method gets a copy of the array. It gets a copy of the reference; the elements are shared.
Thinking reassigning the parameter changes the caller. items = new int[3]; only changes the method's own copy of the reference.
Returning null for "no results". Return an empty array, new int[0], so callers can loop without checking for null.
Interview Corner
Is an array passed by value or by reference in Java?
By value, like everything in Java. The value passed is a copy of the reference to the array. The method can change the array's elements through that copy, and the caller sees the changes, but assigning a new array to the parameter doesn't affect the caller's variable.
Practice
- Easy: Write
static int sum(int[] values)that returns the total of an array, and call it frommain. - Harder: Write
static int[] evens(int[] values)that returns a new array containing only the even numbers. Hint: count them first to know the new array's size.
Key Takeaways
Was this tutorial helpful?