Skip to main content
← AP CSA Study Guide

Code Scholars Tutoring · AP Computer Science A

7.1: Methods and Parameters

Java passes arguments by value. A primitive parameter receives a copied value; an object parameter receives a copied reference that can still refer to the same object.

College Board Unit 1

How it works

Java passes everything by value. For a primitive, the method receives a copy of the number, so changing the parameter has no effect on the caller. For an object or array, the method receives a copy of the reference, which still points at the same underlying object. That means the method can mutate the object through it, but reassigning the parameter to a new object only changes the local copy.

Decide for each parameter whether the method can affect the caller, and trace accordingly.

Common error

Expecting a method to change a caller’s int, or expecting reassigning an object parameter to affect the caller.

Worked example

Java

int[] values = {4, 5};
int[] alias = values;
alias[0] = 9;
System.out.println(values[0]);

Output

9

Copying a reference does not copy the referenced array. Mutation is visible through both references.

Exercises

7.1.1 · Trace

Determine the exact output. Explain the Java rule or state changes that produce it.

Java

int n = 7;
int copy = n;
copy += 3;
System.out.println(n + ":" + copy);
Show solution

Output

7:10

The primitive value is copied into a distinct variable; modifying it does not change n.

7.1.2 · Write code

Write public static void bump(int[] values, int delta). Add delta to each array element. The array mutation must be visible to the caller.

Show solution

One valid solution is shown below. Other implementations satisfying the contract are also valid.

Java

public static void bump(int[] values, int delta) {
    for (int i = 0; i < values.length; i++) values[i] += delta;
}

Check your code

Java

int[] a = {1,3}; bump(a,2); System.out.println(Arrays.toString(a));
int[] b = {}; bump(b,2); System.out.println(Arrays.toString(b));

Expected output

[3, 5]
[]
Practice this topic: MCQ →

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic