ProgrammingVery hardIBM · Deloitte pattern
What is printed?
What is printed?
public class Main {
public static void main(String[] args) {
int i = 0;
while (true) {
try {
i++;
if (i == 3) break;
if (i == 2) continue;
System.out.print(i + " ");
} finally {
System.out.print("f" + i + " ");
}
}
System.out.print("done");
}
}- A. 1 f1 f2 f3 done
- B. 1 f1 f2 continue f3 done
- C. f1 1 f2 f3 done
- D. 1 f1 f2 f3 break done
Correct answer: A. 1 f1 f2 f3 done
finally still runs even when the try block exits via continue or break, not just via normal fall-through. i=1: prints "1 " then "f1 "; i=2: continue skips the print but finally still runs "f2 "; i=3: break skips the print, finally runs "f3 ", then the loop exits and "done" prints.
More OOP with C++ and Java questions
- What is printed? java static int f() { int x = 1; try { return x; } finally { x = 2; } } public static void main(String[] a) {…
- What is printed? java static void f() throws Exception { try { throw new RuntimeException("A"); } finally { throw new…
- What is printed? java for (int i = 0; i < 3; i++) { try { if (i == 1) continue; System.out.print(i); } finally { System.out.print("f"); } }
- What is printed? java try { try { throw new java.io.IOException("io-fail"); } catch (java.io.IOException e) { throw new…
- What happens when this runs? java class Test { static void m() { throw new ArithmeticException("boom"); } public static void main(String[]…
- What is printed? java static void m(int x) throws java.io.IOException, InterruptedException { if (x == 0) throw new java.io.IOException()…