ProgrammingVery hardProduct-company placement · GATE CS
What is printed?
What is printed?
static int f() {
int x = 1;
try { return x; } finally { x = 2; }
}
static StringBuilder g() {
StringBuilder sb = new StringBuilder("a");
try { return sb; } finally { sb.append("b"); }
}
// in main:
System.out.print(f() + " " + g());- A. 1 ab
- B. 2 ab
- C. 1 a
- D. 2 a
Correct answer: A. 1 ab
The return value is evaluated and saved before finally runs. For int that saved value is 1, so changing x does not matter; for g the saved value is a reference to the same StringBuilder, which finally then modifies.
More OOP with C++ and Java questions
- What is printed? java static void m(StringBuilder a, StringBuilder b) { a.append("1"); b = a; b.append("2"); } // in main: StringBuilder x…
- What is printed? java char c = 'a'; c += 1; System.out.print(c + 1); System.out.print(" " + c + 1);
- Which statement about this code is correct? java Object[] arr = new String[2]; // L1 arr[0] = "a"; // L2 arr[1] = Integer.valueOf(1); //…
- What is printed? java int i = 5; i = i++ + ++i; System.out.print(i);
- What is printed? java class A { Object get() { return "A"; } void set(String s) { System.out.print("A.set "); } } class B extends A {…
- What is printed? java Long a = 1L; System.out.print(a.equals(1) + " " + a.equals(1L) + " " + (a == 1));