Arguments, arrays and varargs
Java has one argument-passing rule: everything is passed by value. For a primitive the value is the number; for an array or an object the value is the reference. A method cannot change the caller's variable, and it can change the object the variable points at, which is the distinction this lesson makes with two calls.
Arguments are passed by value
The parameter is a new local variable, initialised with a copy of the argument. Assigning to the parameter changes the copy, and the copy is gone when the method returns.
The file ByValue.java makes both calls:
public class ByValue {
public static void main(String[] args) {
int number = 5;
change(number);
System.out.println("number: " + number);
int[] values = {1, 2, 3};
changeFirst(values);
System.out.println("first: " + values[0]);
}
static void change(int n) {
n = 99;
}
static void changeFirst(int[] data) {
data[0] = 99;
}
}
javac -Xlint:all ByValue.java
java ByValue
number: 5
first: 99
change received 5, wrote 99 into its own copy and returned; the caller still has 5. changeFirst received a copy of the reference, and both references point at the same array, so writing through one is visible through the other.
An array argument
An array is an object, and its length is fixed when it is created. A method that sorts, fills or reverses an array therefore does its work in place and returns nothing, or returns a new array it built itself. The difference matters to the caller:
import java.util.Arrays;
public class InPlace {
public static void main(String[] args) {
int[] values = {3, 1, 4, 1, 5};
Arrays.sort(values);
System.out.println(Arrays.toString(values));
int[] copy = Arrays.copyOf(values, values.length);
copy[0] = 99;
System.out.println(Arrays.toString(values));
System.out.println(Arrays.toString(copy));
}
}
javac -Xlint:all InPlace.java
java InPlace
[1, 1, 3, 4, 5]
[1, 1, 3, 4, 5]
[99, 1, 3, 4, 5]
sort changed the array the caller passed, while copyOf returned a new one, and changing the copy left the original alone. A method that must not change its argument copies it first, and that copy is what a later lesson on immutability calls a defensive copy.
Varargs
int... values declares a parameter that takes any number of arguments, including none. The compiler packs them into an array, so inside the method it is an ordinary int[] with a length.
public class Varargs {
public static void main(String[] args) {
System.out.println(sum());
System.out.println(sum(1));
System.out.println(sum(1, 2, 3));
System.out.println(join(", ", "a", "b", "c"));
}
static int sum(int... values) {
int total = 0;
for (int value : values) {
total += value;
}
return total;
}
static String join(String separator, String... parts) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
if (i > 0) {
builder.append(separator);
}
builder.append(parts[i]);
}
return builder.toString();
}
}
javac -Xlint:all Varargs.java
java Varargs
0
1
6
a, b, c
A varargs parameter must be the last one, because the compiler has to know where the fixed arguments end. A call may also pass an array directly, as in sum(new int[] {1, 2, 3}), which is what the compiler builds for the call above.
main(String[] args)
The launcher collects the words after the class name into the array it passes to main. With no words the array is empty, not null, so args.length is always safe to read.
public class Args {
public static void main(String[] args) {
System.out.println("count: " + args.length);
for (String arg : args) {
System.out.println("arg: " + arg);
}
}
}
javac -Xlint:all Args.java
java Args
count: 0
Run as java Args one two, the same class prints count: 2 and then the two words. The array is made by the launcher, so a program that must parse numbers from it calls Integer.parseInt on each element and reports a usage message when the count is wrong, which is the subject of lesson 031.
Exercises
- Change change in ByValue.java to return the new number, and use the returned value in main.
- Write a method static void reverse(int[] data) that reverses in place and prints the array before and after.
- Add a call sum(new int[] {4, 5}) to Varargs.java. Does it print the same as sum(4, 5)?
- Run Args with three words and predict the output before you run it.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
How does Java pass an argument to a method?
Answer
By value: the parameter gets a copy of the value or the reference
Every argument is copied; for an object the copied value is the reference.
-
Why can a method change an array element of its caller?
Answer
The copied reference points at the same array object
The reference is copied, but both copies point at one array, so a write through either is visible.
-
Where may a varargs parameter stand?
Answer
Last in the parameter list
The compiler collects the remaining arguments into the varargs array, so nothing may follow it.
-
What does this program print?
public class Q1 { public static void main(String[] args) { int n = 1; change(n); System.out.println(n); } static void change(int value) { value = 5; } }Answer
1
The parameter is a copy, so assigning 5 to it leaves the caller variable at 1.
-
What does this program print?
public class Q2 { public static void main(String[] args) { int[] data = {1, 2, 3}; change(data); System.out.println(data[1]); } static void change(int[] values) { values[1] = 9; } }Answer
9
The method writes through a copy of the reference into the same array, so element 1 is 9.
-
What does this program print?
public class Q3 { public static void main(String[] args) { System.out.println(sum(1, 2, 3, 4)); } static int sum(int... values) { int total = 0; for (int value : values) { total += value; } return total; } }Answer
10
The four arguments become an array of four values, and their sum is 10.
-
This program is run with
java Q4 one two. What does it print?public class Q4 { public static void main(String[] args) { System.out.println(args.length + " " + args[0]); } }Answer
2 one
The class name is not an argument; the two words after it are the two elements of the array.
-
What does this program print?
public class Q5 { public static void main(String[] args) { System.out.println(join("-", "a", "b")); } static String join(String separator, String... parts) { String result = ""; for (int i = 0; i < parts.length; i++) { if (i > 0) { result += separator; } result += parts[i]; } return result; } }Answer
a-b
The separator is added only between the parts, so the result is a-b.
-
What does this program print?
public class Q6 { public static void main(String[] args) { int[] values = {1, 2, 3}; int[] copy = values; copy[0] = 7; System.out.println(values[0]); } }Answer
7
The assignment copies the reference, so both names point at one array and the write is visible through both.
-
What does an array parameter receive from the caller?
Answer
A copy of the reference to the array
The parameter holds the same reference value as the argument, which is what makes in-place methods work.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev