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);
    }
}
  1. A. Counter(7) Counter(7)
  2. B. Counter(5) Counter(7)
  3. C. Counter(5) Counter(5)
  4. 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

Exams that ask this topic