LearnFrenzy
Sign in Take a free test

Object Class and Wrapper Classes · Predict the Output · Question 7

Clone with a copied mutable field Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

What is the output of the following Java program?

Main.java
class Point implements Cloneable {
    int x, y;
    int[] history = new int[2];

    @Override public Point clone() {
        try {
            Point p = (Point) super.clone();
            p.history = history.clone();          // deep-copy the array
            return p;
        } catch (CloneNotSupportedException e) { throw new AssertionError(e); }
    }
}

public class Main {
    public static void main(String[] args) {
        Point a = new Point();
        a.x = 3; a.history[0] = 7;
        Point b = a.clone();
        b.x = 5; b.history[0] = 9;
        System.out.println(a.x + " " + a.history[0] + " " + b.x + " " + b.history[0] + " " + (a != b) + " " + (a.getClass() == b.getClass()));
    }
}
  • A 3 7 5 9 true true Correct
  • B 5 9 5 9 true true
  • C 3 9 5 9 true true
  • D 3 7 5 9 false true
Correct Answer: Option A

Primitive fields are copied by value; the array was cloned separately, so the two points are independent.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links