ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
class K {
    static int made = 0;
    K(int v) { made++; if (v < 0) throw new IllegalArgumentException(); }
}
// in main:
for (int v : new int[]{1, -1, 2})
    try { new K(v); } catch (IllegalArgumentException e) { }
System.out.print(K.made);
  1. A. 2
  2. B. 3
  3. C. 1
  4. D. 0

Correct answer: B. 3

The counter is incremented before the check, so the failed construction still counts even though no usable object results. Validate arguments before changing shared state.

More OOP with C++ and Java questions

Exams that ask this topic