ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
public int test() {
try {
return 1;
} finally {
System.out.println("finally");
}
}
// caller: System.out.println(test());- A. 1\nfinally
- B. Compilation error: cannot return from try with a finally present
- C. finally\nfinally
- D. finally\n1
Correct answer: D. finally\n1
The finally block always executes before the method actually returns to its caller, even though the return value (1) was already computed and 'queued' by the try block. So "finally" prints first, then the caller's println outputs 1.
More OOP with C++ and Java questions
- What is printed? java public int test() { try { return 1; } finally { return 2; } } // caller prints test()
- 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));