ProgrammingVery hardProduct company OA
What is printed?
What is printed?
public int test() {
try {
return 1;
} finally {
return 2;
}
}
// caller prints test()- A. 1
- B. 2
- C. Compilation error: duplicate return
- D. 1 then 2
Correct answer: B. 2
A return statement inside finally completely overrides (discards) any pending return from the try block — the finally block's return is the one that actually takes effect, so the method returns 2. This is widely considered bad practice precisely because it silently swallows the original return value (and would even swallow a pending exception).
More OOP with C++ and Java questions
- What is printed? java class MyChecked extends Exception {} class Test { static void risky() throws MyChecked { throw new MyChecked(); }…
- What is printed? java try { try { throw new RuntimeException("inner"); } finally { System.out.print("inner-finally "); } } catch…
- What is printed? java class A { } class B extends A { } class Test { public static void main(String[] args) { A a = new B(); try { B b =…
- What is printed? java List<String> strings = new ArrayList<>(); List<Integer> ints = new ArrayList<>()…
- What is printed? java Integer a = 127; Integer b = 127; Integer c = 200; Integer d = 200; System.out.println((a == b) + " " + (c == d));
- What is printed? java class Base { public void show() { System.out.print("Base "); } } class Derived extends Base { protected void show()…