Common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most copying bugs come from one question asked too late: after this copy, which parts are still shared? Each mistake below either shares something that should be separate, or separates something that should be shared.
Mistakes and fixes at a glance
The most common slip is a deep copy that stops one level early. Every class must copy its own changeable fields, or a part deep inside is still shared.
Example 1 · Bug hunt: a deep copy that stops one level early
import java.util.Arrays;
class Section { String title; int[] questionMarks;
Section(String title, int[] questionMarks) { this.title = title; this.questionMarks = questionMarks; }
Section(Section other) { this.title = other.title; this.questionMarks = other.questionMarks; }
int total() { int sum = 0; for (int m : questionMarks) { sum += m; } return sum; }}
class QuestionPaper { String set; Section[] sections;
QuestionPaper(String set, Section[] sections) { this.set = set; this.sections = sections; }
QuestionPaper(QuestionPaper other) { this.set = other.set; this.sections = new Section[other.sections.length]; for (int i = 0; i < other.sections.length; i++) { this.sections[i] = new Section(other.sections[i]); } }
@Override public String toString() { String text = "Set " + set + ":"; int total = 0; for (Section s : sections) { text = text + " " + s.title + " " + Arrays.toString(s.questionMarks); total += s.total(); } return text + " = " + total; }}
public class QuestionPaperBugDemo { public static void main(String[] args) { QuestionPaper setA = new QuestionPaper("A", new Section[] { new Section("Part A", new int[] {2, 2, 2}), new Section("Part B", new int[] {10, 10}) });
QuestionPaper setB = new QuestionPaper(setA); setB.set = "B"; setB.sections[1].questionMarks[0] = 16;
System.out.println(setA); System.out.println(setB); }}Set A: Part A [2, 2, 2] Part B [16, 10] = 32 Set B: Part A [2, 2, 2] Part B [16, 10] = 32
What this code does
- The examiner made set B from set A and gave one long answer 16 marks. Set A changed from 26 to 32 marks, even though
QuestionPapercopied everySection. - The bug is one level down:
Section's copy constructor sharesquestionMarks. Fix:this.questionMarks = other.questionMarks.clone();.
Review: Shallow vs deep copy (opens in a new tab). The other common mistakes, each with what goes wrong and the fix:
b = afor a template, a backup or a "what if" change → one object, two names; make a copy withnew. Review: Assignment is not a copy (opens in a new tab)- A copy constructor copies an array with
=→ both objects share it; writeother.marks.clone(). Review: Copy constructors (opens in a new tab) clone()orArrays.copyOfon an array of objects taken as a deep copy → new array, same objects; copy each element. Review: Shallow vs deep copy (opens in a new tab)- A field missing from a copy constructor → the copy gets
0,falseornull; chain withthis(...). Review: Copy constructors (opens in a new tab) marks.clone()instead ofother.marks.clone()→ the new object's own field is stillnull:NullPointerException. Review: Copy constructors (opens in a new tab)clone() has protected access,CloneNotSupportedException,cannot assign a value to final variable→ apublicoverride,implements Cloneable, nofinalon cloned fields. Review: clone() and Cloneable (opens in a new tab)
Mistakes that copy too much
Copying can go wrong the other way too. A teacher who takes both the theory course and its lab is one real person; copying her gives two objects that drift apart.
Example 2 · Mistake: copying a part that should be shared
class Teacher { String name; String phone;
Teacher(String name, String phone) { this.name = name; this.phone = phone; }
Teacher(Teacher other) { this(other.name, other.phone); }}
class Course { String code; Teacher teacher;
Course(String code, Teacher teacher) { this.code = code; this.teacher = teacher; }
Course(Course other) { this.code = other.code; this.teacher = new Teacher(other.teacher); }}
public class OverCopyDemo { public static void main(String[] args) { Teacher rao = new Teacher("Prof. Rao", "98450 11111"); Course theory = new Course("CS201", rao);
Course lab = new Course(theory); lab.code = "CS201L"; rao.phone = "98450 22222";
System.out.println(theory.code + ": call " + theory.teacher.phone); System.out.println(lab.code + ": call " + lab.teacher.phone); System.out.println("Same teacher? " + (theory.teacher == lab.teacher)); }}CS201: call 98450 22222 CS201L: call 98450 11111 Same teacher? false
What this code does
- Prof. Rao teaches both the theory course and its lab. The deep copy made a second Rao object, so the lab still shows his old number.
- Fix:
this.teacher = other.teacher;. A part that is one real thing should be shared, not copied.
Keep the reference for a part shared on purpose: this.teacher = other.teacher;. String and enum fields need no copy either: they can never change. Review: Shallow vs deep copy (opens in a new tab)
Test every copy
A copy can look right and still share a hidden part. Three checks catch almost every copying bug: a separate object, the same data, and a change test on every changeable part.
Example 3 · Testing a copy: separate, same data, independent
import java.util.Arrays;import java.util.Objects;
class Marksheet { String name; int roll; int[] marks;
Marksheet(String name, int roll, int[] marks) { this.name = name; this.roll = roll; this.marks = marks; }
Marksheet shallowCopy() { return new Marksheet(name, roll, marks); }
Marksheet deepCopy() { return new Marksheet(name, roll, marks.clone()); }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Marksheet other = (Marksheet) obj; return roll == other.roll && name.equals(other.name) && Arrays.equals(marks, other.marks); }
@Override public int hashCode() { return Objects.hash(name, roll); }}
public class CopyCheckDemo { static void check(String label, Marksheet original, Marksheet copy) { boolean separate = original != copy; boolean sameData = original.equals(copy);
int before = original.marks[0]; copy.marks[0] = before + 10; boolean independent = original.marks[0] == before; copy.marks[0] = before;
System.out.println(label + ": separate=" + separate + ", sameData=" + sameData + ", independent=" + independent); }
public static void main(String[] args) { Marksheet kavya = new Marksheet("Kavya", 21, new int[] {78, 64, 91});
check("assigned", kavya, kavya); check("shallow", kavya, kavya.shallowCopy()); check("deep", kavya, kavya.deepCopy()); }}assigned: separate=false, sameData=true, independent=false shallow: separate=true, sameData=true, independent=false deep: separate=true, sameData=true, independent=true
What this code does
- All three "copies" have the same data, so
equals()alone cannot tell them apart. The==check and the change test can. - Only the deep copy passes all three checks.
checkputs the mark back afterwards, so the next test starts clean.hashCode()uses onlynameandroll, which is still valid: equal marksheets get equal hash codes.
Right after copying, a copy should be equals() to its original, as in equals() (opens in a new tab); if not, a field was forgotten. Parts shared on purpose pass the opposite test: copy.teacher == original.teacher must stay true.
Spot the bug
Each snippet below should make an independent copy, or share exactly what is meant to be shared. Read what it should do, tap the wrong line, then check the fix.
Find the bug
Find the copying bug
Select the line that is wrong.
The copy of a Marksheet must not share its marks.
Round 1 of 5Trace before you guess
When a copy surprises you, trace it with names for the objects. Ask for every line: does it change a slot of one array, or an object that two arrays share?
Trace the code
Trace an array copy
Variables
- booked
- A: [X=12, Y=13]
Output
(nothing printed yet)Line 11Two Seat objects, X (12) and Y (13), sit in array A. booked points to A.
Finish up
Mark complete & continue
Next: Must-do problems: Copying Objects