ProgrammingVery hardProduct company OA
What is printed?
What is printed?
static int f() {
int x = 1;
try {
return x;
} finally {
x = 2;
}
}
public static void main(String[] a) { System.out.print(f()); }- A. 1
- B. 2
- C. Compilation error
- D. 0
Correct answer: A. 1
For a primitive, the try's return value (1) is copied before finally executes. finally mutating x afterward does not change the already-captured return value, so 1 is printed, not 2.
More OOP with C++ and Java questions
- 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()…
- What happens when this runs, assuming recurse() causes infinite recursion? java static void recurse() { recurse(); } public static void…