ProgrammingVery hardIBM · Deloitte pattern
What is printed?
What is printed?
public class Main {
public static void main(String[] args) {
int result = compute();
System.out.println(result);
}
static int compute() {
int x = 5;
try {
x = x / 0;
return x;
} catch (ArithmeticException e) {
return -1;
} finally {
x = 100;
System.out.print("x-in-finally=" + x + " ");
}
}
}- A. x-in-finally=100 -1
- B. x-in-finally=100 100
- C. ArithmeticException propagates uncaught
- D. x-in-finally=5 -1
Correct answer: A. x-in-finally=100 -1
x / 0 for ints throws ArithmeticException, caught by the catch block, which computes a return value of -1 (saved before finally runs). finally then sets x = 100 and prints it, but that assignment doesn't change the already-decided return value, so compute() still returns -1.
More OOP with C++ and Java questions
- 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) {…
- What is printed? java class MyException extends RuntimeException { MyException(String m) { super(m); } } public class Main { public static…
- What is printed? java public class Main { public static void main(String[] args) { int i = 0; while (true) { try { i++; if (i == 3) break…
- What is printed? java static int f() { int x = 1; try { return x; } finally { x = 2; } } public static void main(String[] a) {…