ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Base implements Cloneable {
    int x = 5;
    @Override
    public Base clone() throws CloneNotSupportedException {
        return (Base) super.clone();
    }
}
// in main:
Base b1 = new Base();
Base b2 = b1.clone();
b2.x = 99;
System.out.println(b1.x + " " + b2.x + " " + (b1 == b2));
  1. A. 5 99 false
  2. B. 99 99 true
  3. C. 5 5 false
  4. D. 5 99 true

Correct answer: A. 5 99 false

Object.clone() performs a shallow field-by-field copy into a NEW object, so b2 is a distinct object (b1 == b2 is false) starting with the same x=5; mutating b2.x to 99 only affects b2's own copy, leaving b1.x at 5.

More OOP with C++ and Java questions

Exams that ask this topic