ProgrammingVery hardAmazon/Microsoft SDE MCQ · Java placement
What is printed?
What is printed?
// static methods of the main class:
static int f() {
int x = 1;
try { return x; } finally { x = 5; }
}
static StringBuilder g() {
StringBuilder sb = new StringBuilder("hi");
try { return sb; } finally { sb.append("x"); }
}
// in main:
System.out.print(f() + " " + g());- A. 1 hix
- B. 5 hix
- C. 1 hi
- D. 5 hi
Correct answer: A. 1 hix
The return value is saved before finally runs. For f it is the int 1, so changing x later has no effect. For g it is a reference to the StringBuilder, and finally mutates that same object, so the caller sees hix.
More OOP with C++ and Java questions
- What is printed? java class A { static int x = f(); static int y = 10; static int f() { return y 2; } } // in main: System.out.print(A.x +…
- What is printed? java class P { P() { show(); } void show() { System.out.print("P"); } } class C extends P { int v = 7; String s = "x"…
- Which statement about this code is correct? java try { new java.io.FileReader("a.txt").close(); } catch (java.io.IOException | Exception…
- What is printed? java class A { void m(A a) { System.out.print("AA"); } } class B extends A { void m(A a) { System.out.print("BA"); } void…
- Which lines fail to compile? java List<Integer> ints = new ArrayList<>(); List<Number> a = ints; // line 1 List<? extends Number> b =…
- What happens? java boolean flag = true; Integer none = null; Integer r1 = flag ? null : 0; System.out.print(r1); Integer r2 = flag ? none…