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);- A. 9 5
- B. 1 5
- C. 9 7
- 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
- What is printed? java // static method of the main class: static void swap(int[] a, int[] b) { int[] t = a; a = b; b = t; a[0] = 100; } //…
- What is printed? java Object o = "hi"; String s = (String) o; Integer n = null; System.out.print((n instanceof Integer) + " " + (o…
- What is printed? java class A { static int v = 1; static int get() { return v; } } class B extends A { static int v = 2; } // in main…
- What happens when this code is compiled? java try { new java.io.FileReader("x.txt"); } catch (Exception e) { System.out.print("E"); }…
- What is printed? java // static method of the main class: static int f() { try { throw new RuntimeException("t"); } finally { return 7; }…
- What is printed? java try { try { throw new IllegalStateException("A"); } finally { throw new IllegalArgumentException("B"); } } catch…