ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
// static method of the main class:
static int f() {
try { throw new RuntimeException("t"); }
finally { return 7; }
}
// in main:
try { System.out.print(f()); }
catch (RuntimeException e) { System.out.print("caught"); }- A. caught
- B. 7caught
- C. 7
- D. Compile-time error: missing return
Correct answer: C. 7
A return in finally completes the method normally and silently discards the pending exception, so f() returns 7 and nothing is caught. (This is why returning from finally is considered bad practice.)
More OOP with C++ and Java questions
- What is printed? java try { try { throw new IllegalStateException("A"); } finally { throw new IllegalArgumentException("B"); } } catch…
- What is printed? java class K { static int v = 10 / Integer.parseInt("0"); } // in main: try { System.out.print(K.v); } catch…
- What is printed? java // static method of the main class: static void down() { down(); } // in main: try { down(); } catch (Exception e) {…
- What happens when this class is compiled? java class A { A() { this(1); } A(int x) { this(); } }
- What is printed? java class A { void f() { System.out.print("Af "); g(); } void g() { System.out.print("Ag "); } } class B extends A {…
- What is printed? java class Pt { int x; Pt(int x) { this.x = x; } public boolean equals(Object o) { return o instanceof Pt && ((Pt) o).x…