ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
public class Main {
static int risky() {
try {
return 1;
} finally {
return 2;
}
}
public static void main(String[] args) {
System.out.println(risky());
}
}- A. 1
- B. 2
- C. Compilation error: finally cannot contain return
- D. It throws an exception at run time
Correct answer: B. 2
A return inside finally discards any pending return (or exception) from the try block and becomes the method's actual result, so even though try computes 1 first, finally's return 2 overrides it and 2 is what's returned.
More OOP with C++ and Java questions
- What is printed? java class MyChecked extends Exception { MyChecked(String m) { super(m); } } public class Main { static void risky()…
- Which statement about this code is correct? java class Main { static void risky() { if (Math.random() < 2) throw new…
- What is printed? java public class Main { public static void main(String[] args) { int result = compute(); System.out.println(result); }…
- What is printed? java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); try {…
- What is printed? cpp struct Logger { Logger() { cout << "open "; } ~Logger() noexcept(false) { cout << "close "; throw…
- What is printed? java public class Main { public static void main(String[] args) { try { level1(); } catch (RuntimeException e) {…