ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
public class Main {
static int f() {
int x = 10;
try {
return x;
} finally {
x = 20;
}
}
public static void main(String[] a) { System.out.println(f()); }
}- A. 20
- B. 10
- C. Compile-time error: x is modified after being returned
- D. 0
Correct answer: B. 10
return x evaluates and saves the return value (10) before finally runs. finally then reassigns the local variable x, but that happens too late to affect the value already captured for return, so the method returns 10.
More OOP with C++ and Java questions
- What is printed? java public class Main { public static void main(String[] a) { try { System.out.print("A"); throw new RuntimeException()…
- Does this compile? java class MyException extends Exception {} class Demo { void risky() throws MyException { throw new MyException(); }…
- Does this compile? java class Demo { void risky() { throw new IllegalArgumentException(); } void call() { risky(); } }
- What is printed? java public class Main { public static void main(String[] a) { int[] arr = {1, 2, 3}; try { System.out.print(arr[5]); }…
- What is printed? java public class Main { static void a() { b(); } static void b() { c(); } static void c() { throw new…
- Does this compile? java public class Main { public static void main(String[] a) { try { throw new RuntimeException(); } catch (Exception…