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");
    }
}
  1. A. 1 f1 f2 f3 done
  2. B. 1 f1 f2 continue f3 done
  3. C. f1 1 f2 f3 done
  4. 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

Exams that ask this topic