Skills101
← All practice quizzes

Quiz: Shallow and Deep Copy

5 questions · new set on every retakeNo time limitPass: 60%+10 XP on first pass

Why changing a "copy" sometimes changes the original too. Learn the difference between assignment, shallow copy and deep copy in Java, how clone() really works, and why copy constructors are usually the better choice.

Log in to take the quiz

Free account · see your score, answers and explanations, earn XP

  1. Question 1

    What does this print?

    class Box {
        int value;
        Box(int value) { this.value = value; }
    }
    
    public class Main {
        public static void main(String[] args) {
            Box a = new Box(5);
            Box b = a;
            b.value = 10;
            a = new Box(20);
            System.out.println(a.value + " " + b.value);
        }
    }
    
  2. Question 2

    In a shallow copy, what happens to a field that refers to another object?

  3. Question 3

    What does super.clone() do inside a class that implements Cloneable?

  4. Question 4

    What does this print?

    import java.util.*;
    
    class Team implements Cloneable {
        List<String> members = new ArrayList<>();
    
        @Override
        public Team clone() {
            try { return (Team) super.clone(); }
            catch (CloneNotSupportedException e) { throw new AssertionError(e); }
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Team t1 = new Team();
            t1.members.add("Asha");
            Team t2 = t1.clone();
            t2.members.add("Ravi");
            System.out.println(t1.members.size() + " " + t2.members.size());
        }
    }
    
  5. Question 5

    A class has fields String name, int age and List<Address> addresses (Address is mutable). What must a correct deep copy do?

🎯 Today’s placement challenge — 10 questions, no login. Can you score 10/10?Take today’s challenge →