ProgrammingHardTCS NQT · Infosys · Accenture
What does this Java program print? static int f() { int x = 1; try { return x; } finally { x = 3; } } static int g() { try { throw new RuntimeException(); } finally { return 5; } } // in main: System.out.println(f() + g());
- A. 8
- B. 4
- C. 6
- D. RuntimeException is thrown
Correct answer: C. 6
In f the return value 1 is saved before the finally block runs, so changing x to 3 has no effect. In g, the return inside finally overrides and discards the exception, so g returns 5. The total is 1 + 5 = 6.
More OOP with C++ and Java questions
- What does this C++ program print? struct B { B() { f(); } virtual void f() { std::cout << "B"; } }; struct D : B { D() { f(); } void f()…
- What does this C++ program print? struct B { virtual void f(int x = 1) { std::cout << "B" << x; } }; struct D : B { void f(int x = 2)…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct B { virtual void f(int x = 1) { cout << "B" << x; } }…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct B { void f(int) { cout << "Bi"; } void f(double) { cout <<…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct T { T() { cout << "T"; } ~T() { cout << "~"; } }; void g()…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct R { const char n; R(const char s) : n(s) { cout << "+" <<…