ProgrammingHardGATE CS · TCS Digital · Advanced

What is printed?

What is printed?
static int f() {
    try { throw new RuntimeException(); }
    finally { return 1; }
}
static int g() {
    int x = 1;
    try { return x; }
    finally { x = 2; }
}
static int[] h() {
    int[] a = {1};
    try { return a; }
    finally { a[0] = 2; }
}
// in main:
System.out.print(f() + " " + g() + " " + h()[0]);
  1. A. 1 1 2
  2. B. 1 2 2
  3. C. 2 1 2
  4. D. 1 1 1

Correct answer: A. 1 1 2

A return in finally discards the exception (f gives 1). g's return value was already evaluated before finally changed x, so it stays 1; h returns a reference to the array, so the change a[0] = 2 is visible.

More OOP with C++ and Java questions

Exams that ask this topic