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);- A. 2
- B. 3
- C. 1
- 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
- What is printed? java interface Named { default String n() { return getClass().getSimpleName(); } } class Dog implements Named { } // in…
- What is printed? java Runnable r = new Runnable() { public void run() { } }; System.out.print("[" + r.getClass().getSimpleName() + "]" +…
- Which line fails to compile? java class P { final void f(int x) { } } class C extends P { void f(long x) { } // L1 void f(int y) { } // L2 }
- What is printed? java class P { int x; P(int x) { this.x = x; } public boolean equals(Object o) { return o != null && getClass() ==…
- What is printed? java Boolean b1 = true, b2 = true; Character c1 = 'a', c2 = 'a'; Short s1 = 100, s2 = 100; System.out.print((b1 == b2) +…
- What is printed? java List<Integer> l = Arrays.asList(3, 1, 2); Collections.sort(l); System.out.print(l + " "); l.clear();