Java passes every argument by value: the parameter receives a copy of the argument's value. For a primitive such as an int, the copy is the number itself, so changing the parameter never changes the caller's variable. For an object, the copy is a reference, so the method can change the object that both variables point to, but reassigning the parameter never changes which object the caller's variable refers to.
Quick check
What does return total; do in a method whose return type is int?Show answerHide answer
It ends the method and hands the value of
totalback to the caller.After Counter a = new Counter(1); Counter b = a;, how many Counter objects exist?Show answerHide answer
One.
newran once;b = acopies the reference, so both variables point to the same object.A method sets its int parameter to 0. Does the caller's int variable change?Show answerHide answer
No. The parameter holds a copy of the value.
Know these already? Jump to the practice questions
What you'll be able to do
- Explain why changing a primitive parameter leaves the argument unchanged.
- Determine how a method changes an object through a reference parameter.
- Explain why reassigning a reference parameter leaves the caller's variable alone.
- Determine which object a returned reference points to.
- Identify when two variables are aliases of one object.
Key terms
Reference
The value stored in an object variable: it says where the object is, not what it contains.
- In plain English
- An arrow pointing at the object.
- Don't write
- "The variable
kis the object."
Pass by value
The rule that a method's parameter gets a copy of the argument's value; Java uses it for every argument.
- In plain English
- The method works on a photocopy of what you hand it.
- Don't write
- "Java passes objects by reference."
Alias
One of two or more references to the same object; a change made through one is seen through the others.
- In plain English
- Two names for one thing.
- Don't write
- "
b = a;makes a second copy of the object."
What does Java copy when you pass an argument?
The examples below all use this Counter class:
public class Counter
{
private int count;
public Counter(int c)
{
count = c;
}
public void add(int n)
{
count = count + n;
}
public int getCount()
{
return count;
}
}
When you call a method, each parameter becomes a new variable holding a copy of its argument's value. With a primitive argument, the copy is the number. A method in a class Changer shows what that means:
public void bump(int n)
{
n = n + 10;
}
After int x = 5; and ch.bump(x);, where ch is a Changer, x is still 5. The method added 10 to n, its own copy, and n vanished when the method ended.
Key idea
A parameter is a separate variable that starts as a copy of the argument.
Check yourself
Show answerHide answer
- Only the copy in
nchanged.
Why can a method change an object you pass it?
An object variable holds a reference. Passing it copies the reference, so the parameter and the argument become aliases: two arrows to one object.
public void bumpCounter(Counter c)
{
c.add(10);
}
After Counter k = new Counter(5); and ch.bumpCounter(k);, k.getCount() is 15. The method followed its copy of the arrow to the same object and changed that object's count. The caller sees the change because k points to the same object.
This is still pass by value. What was copied is the reference, not the object, so no second Counter was made.
Check yourself
Show answerHide answer
One. The parameter c and the variable k both refer to it.
Why can't a method make your variable point somewhere else?
Assigning a new object to a reference parameter moves only the parameter's arrow.
public void replace(Counter c)
{
c = new Counter(99);
}
After ch.replace(k);, k still refers to its original object, with its original count. Inside the method, c was pointed at a new Counter, but c is only a copy of k's reference, so k is untouched. The new object is lost when the method ends.
So a method can change the object (by calling its methods), but it cannot change which object the caller's variable refers to.
Check yourself
Show answerHide answer
Still 15. replace moved only its own copy of the reference.
What happens when a method returns a reference?
A method whose return type is a class returns a reference. It can point to a brand-new object or to one that already exists.
public Counter bigger(Counter a, Counter b)
{
if (a.getCount() >= b.getCount())
{
return a;
}
return b;
}
bigger makes no new object: it returns one of the references it was given. So Counter big = ch.bigger(p, q); makes big an alias of p or of q, and big.add(5) changes that original object.
A method that ends with return new Counter(...) hands back a reference to a fresh object, so changes to it leave every older object alone.
Check yourself
Show answerHide answer
The one p refers to: 3 ≥ 3 is true, so it returns a.
Worked example 1: Primitive, object and reassignment
Question: Using the Counter class from this note and this Changer class, what is printed?
public class Changer
{
public void bump(int n)
{
n = n + 10;
}
public void bumpCounter(Counter c)
{
c.add(10);
}
public void replace(Counter c)
{
c = new Counter(99);
}
}
Changer ch = new Changer();
int x = 5;
Counter k = new Counter(5);
ch.bump(x);
ch.bumpCounter(k);
ch.replace(k);
System.out.println(x + " " + k.getCount());
What tells you the method
Arguments are passed to methods that change their parameters, so track what each parameter is a copy of.
Step 1: Trace each call.
Call Parameter starts as Inside the method xk's objectstart 5 count 5 bump(x)n= 5nbecomes 155 count 5 bumpCounter(k)c→k's objectobject's count + 10 5 count 15 replace(k)c→k's objectc→ new count 995 count 15 WhyOnly the middle call changes something the caller can see: the shared object.
Step 2: Print.
xis 5 andk.getCount()is 15.Whykstill points to its original object.
Check it
Swap the order of the last two calls: replace still changes nothing, and bumpCounter still adds 10, so the output is the same.
Answer
5 15
Worked example 2: Design a method that returns a copy
Question: Design a Changer method copyOf that returns a new Counter with the same count as its argument, so that changing the copy leaves the original alone. Then state what this prints.
Counter a = new Counter(4);
Counter b = ch.copyOf(a);
Counter c = a;
b.add(1);
c.add(10);
String line = a.getCount() + " " + b.getCount();
System.out.println(line + " " + c.getCount());
What tells you the method
A design task: choose the header from the input and output, write the body, then trace.
Step 1: Choose the header.
The input is a
Counterand the output is aCounter:public Counter copyOf(Counter c).WhyThe return type names the kind of reference handed back.
Step 2: Write the body.
public Counter copyOf(Counter c) { return new Counter(c.getCount()); }Whynewmakes a separate object; returningcwould only make an alias.Step 3: Trace.
brefers to a new object with count 4.c = amakescan alias ofa.b.add(1)makes the copy 5;c.add(10)makes the shared object 14.Whyaandcprint the same number because they are one object.
Check it
Two new expressions ran, so there are exactly two Counter objects, matching the two different counts printed.
Answer
14 5 14
Worked example 3: Mixed changes in one method
Question: update is a Changer method, and ch refers to a Changer. Using the Counter class from this note, what is printed?
public void update(Counter c, int n)
{
c.add(n);
n = 0;
c = new Counter(n);
c.add(100);
}
Counter k = new Counter(3);
int v = 4;
ch.update(k, v);
System.out.println(k.getCount() + " " + v);
- A)
7 4 - B)
100 0 - C)
7 0 - D)
3 4
What tells you the method
One method changes an object, a primitive and a reference, so sort which changes reach the caller.
Step 1: Trace the body.
c.add(4)makesk's object 7.n = 0changes only the copy.c = new Counter(0)movescto a new object, andc.add(100)changes that new object.WhyOnly the first line acts on an object the caller can reach.
Step 2: Test the options.
B assumes reassignment and the
intchange both reach the caller. C assumes theintchange does. D assumes the object was copied, so nothing changed.WhyEach wrong option breaks one rule of pass by value.
Check it
v was never on the left of an assignment outside the method, so it must still be 4.
Answer
A
Your turn
Question: ch refers to a Changer with the method bigger below. Using the Counter class from this note, what is printed?
public Counter bigger(Counter a, Counter b)
{
if (a.getCount() >= b.getCount())
{
return a;
}
return b;
}
Counter p = new Counter(6);
Counter q = new Counter(9);
Counter big = ch.bigger(p, q);
big.add(5);
System.out.println(p.getCount() + " " + q.getCount());
Step 1: Find what
biggerreturns.6 ≥ 9 is false, so it returns
b, a reference toq's object.bigis now an alias ofq.Step 2: Your go: apply
big.add(5)and build the printed line.
Show the full solutionHide the solution
Step 2. big.add(5) changes the object q refers to, from 9 to 14. p is untouched at 6.
Answer: 6 14
Traps
Trap
Java passes objects by reference, so assigning a new object to the parameter changes the caller's variable.
It seems right because changes made through the parameter show up in the caller. But the reference itself was copied, so pointing the copy at a new object leaves the caller's variable where it was.
After Counter k = new Counter(5); ch.replace(k);, what does k.getCount() return?
Trap
Returning an object hands the caller a separate copy.
It seems right because return gives back "the answer". But it gives back a reference, so if the method returns an existing object, the caller gets an alias and can change the original.
If bigger(p, q) returns q, does big.add(1) change q's count?
Yes: big and q refer to the same object.
What's examined
On the AP® Computer Science A exam (Unit 3: Class Creation), multiple-choice questions give a method that changes its parameters and ask what is printed afterwards, or which variables refer to the same object. In free response, methods take and return objects, and you need to know whether you are changing an existing object or creating a new one.
Practice questions
The Counter class and these Changer methods are for questions 1 to 5. ch refers to a Changer object.
public class Counter
{
private int count;
public Counter(int c)
{
count = c;
}
public void add(int n)
{
count = count + n;
}
public int getCount()
{
return count;
}
}
public Counter bigger(Counter a, Counter b)
{
if (a.getCount() >= b.getCount())
{
return a;
}
return b;
}
public Counter copyOf(Counter c)
{
return new Counter(c.getCount());
}
- Recall Which statement about
Counter b = a;is true, wherearefers to aCounter?
- A) It creates a second
Counterwith the same count. - B) It copies
a's count into a new variable thatbholds. - C)
aandbnow refer to the same object. - D) It does not compile, because an object must be made with
new.
Show answer
Answer: C. Assigning one object variable to another copies the reference, making b an alias of a.
Why the others are wrong:
- A treats assignment as copying the object; only
newmakes a newCounter. - B treats
bas holding the count; it holds a reference. - D is wrong:
b = a;is a legal reference assignment.
- Exam-style Which
Changermethod, when called asch.resetAll(k), leaves the objectkrefers to with a count of 0?
- A)
public void resetAll(Counter c) { c = new Counter(0); } - B)
public void resetAll(Counter c) { c.add(-c.getCount()); } - C)
public void resetAll(int n) { n = 0; } - D)
public Counter resetAll(Counter c) { return new Counter(0); }
Show answer
Answer: B. It follows the reference to k's object and adds the negative of its count.
Why the others are wrong:
- A points only the parameter at a new object;
k's object keeps its count. - C takes an
int, soch.resetAll(k)does not compile, and a primitive copy could not change the caller anyway. - D returns a new object, but the call ignores the result and
kstill refers to the old object.
- Apply A
Changermethod ispublic void grow(int size, Counter c) { size++; c.add(size); }. After this code, what aresandk.getCount()?
int s = 3;
Counter k = new Counter(10);
ch.grow(s, k);
- A)
sis 3 andk.getCount()is 13 - B)
sis 4 andk.getCount()is 14 - C)
sis 3 andk.getCount()is 10 - D)
sis 3 andk.getCount()is 14
Show answer
Answer: D. size becomes 4 inside the method and 4 is added to the shared object; s keeps its value.
Why the others are wrong:
- A forgets that
size++happens beforec.add(size), so 4 is added, not 3. - B lets the
intparameter change reachs. - C treats the object as copied, so it misses the change.
- Exam-style What is printed?
Counter p = new Counter(2);
Counter q = new Counter(2);
Counter r = ch.bigger(p, q);
r.add(3);
q.add(1);
String line = p.getCount() + " " + q.getCount();
System.out.println(line + " " + r.getCount());
Show answer
Answer: 5 3 5
Marking points:
- 2 ≥ 2 is true, so
biggerreturnsa, makingran alias ofp. r.add(3)makesp's object 5;q.add(1)makesq's object 3.
- Exam-style How many
Counterobjects exist after this code runs?
Counter a = new Counter(1);
Counter b = a;
Counter c = ch.copyOf(b);
Counter d = ch.bigger(a, c);
Show answer
Answer: 2
Marking points:
newruns once in the first line and once insidecopyOf.banddare aliases:biggerreturnsa, since 1 ≥ 1.
- Recall Answer "by value" or "by reference": how does Java pass every argument to a method?
Show answer
Answer: By value.
Marking points:
- For an object, the value copied is the reference.
- Apply What is printed?
public class Doubler
{
public int doubleIt(int n)
{
n = n * 2;
return n;
}
}
Doubler d = new Doubler();
int a = 7;
int b = d.doubleIt(a);
System.out.println(a + " " + b);
Show answer
Answer: 7 14
Marking points:
nstarts as a copy of 7 and becomes 14, which is returned and stored inb.ais never assigned, so it stays 7.
- Apply
Pethas a constructorPet(String n), a methodrename(String n)that sets its name, andgetName(). What is printed?
public class Vet
{
public void treat(Pet p)
{
p.rename("Max");
p = new Pet("Bo");
p.rename("Rex");
}
}
Pet a = new Pet("Ivy");
Vet v = new Vet();
v.treat(a);
System.out.println(a.getName());
Show answer
Answer: Max
Marking points:
- The first line renames the object
arefers to. - After
pis pointed at a newPet, "Rex" goes to that new object, not toa's.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- Every argument is copied into its parameter; for objects the copy is a reference.
- A changed primitive parameter never affects the caller's variable.
- A method can change a passed object through its methods.
- Reassigning a reference parameter never moves the caller's variable.
- A returned reference may be an alias of an existing object.