ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
class Box implements Cloneable {
    int[] data = {1, 2};
    int n = 5;
    public Box clone() throws CloneNotSupportedException { return (Box) super.clone(); }
}
// in main (declared throws Exception):
Box a = new Box();
Box b = a.clone();
b.data[0] = 9;
b.n = 7;
System.out.print(a.data[0] + " " + a.n);
  1. A. 9 5
  2. B. 1 5
  3. C. 9 7
  4. D. 1 7

Correct answer: A. 9 5

Object.clone makes a SHALLOW copy: primitive fields are copied, but the array reference is shared, so writing b.data[0] changes a's array while b.n is b's own copy.

More OOP with C++ and Java questions

Exams that ask this topic