ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
public class Main {
static int divide(int a, int b) {
try {
return a / b;
} catch (ArithmeticException e) {
return -1;
} finally {
System.out.print("cleanup ");
}
}
public static void main(String[] args) {
System.out.println(divide(10, 0));
}
}- A. cleanup -1
- B. Exception in thread "main": ArithmeticException
- C. cleanup then the program crashes
- D. -1 cleanup
Correct answer: A. cleanup -1
10 / 0 throws ArithmeticException, caught by the catch block which decides to return -1; finally still runs before that value is actually handed back, printing "cleanup " first, and only then does println print the returned value, -1.
More OOP with C++ and Java questions
- What is printed? java import java.util.; public class Main { public static void main(String[] args) { Map<String, Integer> m = new…
- What is printed? java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder("abc"); try {…
- What is printed? java class A { A() { System.out.print("A "); } } class B extends A { B() { System.out.print("B "); } B(int x) { this()…
- What happens when this is compiled? java class A { A(int x) { System.out.print("A(int) "); } } class B extends A { B() {…
- What is printed? cpp struct A { A() { cout << "A"; } ~A() { cout << "~A"; } }; struct B { A a; B() { cout << "B"; } ~B() { cout << "~B"; }…
- What is printed? java class Base { protected int val; Base(int v) { val = v; System.out.print("Base(" + val + ") "); } } class Derived…