ProgrammingVery hardProduct company interview · GATE level
What is printed?
What is printed?
// static methods of the main class:
static int f() {
int x = 1;
try {
x = 2;
throw new IllegalStateException();
} catch (IllegalStateException e) {
x = 3;
return x;
} finally {
x = 4;
System.out.print(x + " ");
}
}
static int g() {
try {
throw new RuntimeException("g");
} finally {
return 5;
}
}
// in main:
System.out.print(f() + " ");
System.out.print(g());- A. 3 4 5
- B. 4 4 5
- C. 4 3 5
- D. 4 3 followed by RuntimeException: g
Correct answer: C. 4 3 5
In f, the catch block evaluates return x when x is 3, and that value is saved before finally runs. finally sets x = 4 and prints '4 ', but changing the local variable does not change the saved return value, so f returns 3 and main prints '3 '. In g, the finally block's return completes the method normally and discards the pending RuntimeException, so g returns 5 with no exception. Output: 4 3 5.
More OOP with C++ and Java questions
- What is printed? java Long l = 127L; Integer i = 127; System.out.print(l.equals(127) + " "); System.out.print(l.equals(127L) + " ")…
- What is printed? java // static methods of the main class: static void f(long x) { System.out.print("long "); } static void f(Integer x) {…
- What happens when this code runs? java List<String> strs = new ArrayList<>(); strs.add("a"); List raw = strs; raw.add(42)…
- What is printed? java final String a = "Ja"; String b = "Ja"; String x = a + "va"; String y = b + "va"; String z = y.intern()…
- What is printed? java class K { int id; K(int id) { this.id = id; } public boolean equals(Object o) { return o instanceof K && ((K) o).id…
- What happens when this code runs? java Integer n = null; boolean flag = true; Integer a = flag ? n : Integer.valueOf(0)…