ProgrammingHardGATE CS · TCS Digital · Advanced
What is printed?
What is printed?
static int f() {
try { throw new RuntimeException(); }
finally { return 1; }
}
static int g() {
int x = 1;
try { return x; }
finally { x = 2; }
}
static int[] h() {
int[] a = {1};
try { return a; }
finally { a[0] = 2; }
}
// in main:
System.out.print(f() + " " + g() + " " + h()[0]);- A. 1 1 2
- B. 1 2 2
- C. 2 1 2
- D. 1 1 1
Correct answer: A. 1 1 2
A return in finally discards the exception (f gives 1). g's return value was already evaluated before finally changed x, so it stays 1; h returns a reference to the array, so the change a[0] = 2 is visible.
More OOP with C++ and Java questions
- What is printed? java class K { int v; K(int v) { this.v = v; } public int hashCode() { return v; } public boolean equals(Object o) {…
- What is printed? java Number[] n = new Integer[2]; n[0] = 1; try { n[1] = 2.5; } catch (ArrayStoreException e) { System.out.print("ASE ")…
- What is printed? java String a = "ab"; String b = "a"; String c = b + "b"; final String d = "a"; String e = d + "b"; System.out.print((a…
- What is printed? java interface A { default String m() { return "A"; } } interface B extends A { default String m() { return "B"; } }…
- What is printed? java class P { String n = "P"; static String s() { return "Ps"; } String t() { return "Pt"; } } class C extends P {…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct M { const char n; M(const char s) : n(s) { } ~M() { cout <<…