ProgrammingModerateWipro · Capgemini pattern
What is printed?
What is printed?
class C {
static int n = 0;
C() { n++; }
}
// in main:
for (int i = 0; i < 3; i++) new C();
C c = new C();
System.out.print(c.n);- A. 3
- B. 1
- C. 4
- D. 0
Correct answer: C. 4
n is static, so one copy is shared by all objects and every constructor call adds to it: 3 objects in the loop plus c makes 4. Reading it through c.n still reads the shared field.
More OOP with C++ and Java questions
- In Java, final applied to a class, a method and a variable means, respectively:
- What is printed? java List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(1, 5); System.out.print(list);
- What is printed? java Set<String> s = new HashSet<>(); s.add("a"); s.add("b"); s.add("a"); System.out.print(s.size() + " " + s.add("b"));
- What is printed? java try { System.out.print("T"); throw new RuntimeException(); } catch (Exception e) { System.out.print("C"); } finally…
- Why must a C++ copy constructor take its parameter by reference (A(const A &other)) rather than by value?
- What is printed? java System.out.print("placement".substring(2, 5) + "placement".indexOf('e'));