ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Counter {
int value;
Counter(int v) { value = v; }
Counter increment() { return new Counter(value + 1); }
public String toString() { return "Counter(" + value + ")"; }
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter(5);
Counter c2 = c1.increment().increment();
System.out.println(c1 + " " + c2);
}
}- A. Counter(7) Counter(7)
- B. Counter(5) Counter(7)
- C. Counter(5) Counter(5)
- D. Compile-time error: increment() cannot be chained twice
Correct answer: B. Counter(5) Counter(7)
Counter is treated immutably here: increment() always returns a brand-new Counter rather than modifying value in place, so c1 itself is never changed (stays Counter(5)). c1.increment() creates Counter(6); chaining .increment() on that creates Counter(7), which c2 ends up referencing.
More OOP with C++ and Java questions
- What is printed? cpp struct Animal { virtual ~Animal() {} virtual void speak() const { cout << "..."; } }; struct Dog : Animal { void…
- What is printed? java class A { A() { System.out.print(id() + " "); } int id() { return 0; } } class B extends A { int val; B(int v) { val…
- What is printed? cpp struct Shape { virtual void draw() const { cout << "Shape "; } }; struct Group : Shape { std::vector<Shape> children…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { void f() override { cout << "B"; } }; struct C : B {…
- Does this compile? java public class Main { public static void main(String[] args) { try { throw new RuntimeException("x"); } catch…
- What is printed? java public class Main { public static void main(String[] args) { try { Object[] arr = new String[3]; arr[0] = 100; }…