ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
class T {
String name = "outer";
void run() {
Runnable a = () -> System.out.print(this.name + " ");
Runnable b = new Runnable() {
String name = "anon";
public void run() { System.out.print(this.name); }
};
a.run(); b.run();
}
}
// in main:
new T().run();- A. anon anon
- B. outer outer
- C. outer anon
- D. Compile-time error: this cannot be used in a lambda
Correct answer: C. outer anon
A lambda does not introduce a new scope for this: it refers to the enclosing T. An anonymous class is a real class, so its this is the anonymous object with its own name field.
More OOP with C++ and Java questions
- What is printed? java // Java 16 or later record P(int x, int y) { } // in main: P a = new P(1, 2), b = new P(1, 2); System.out.print((a…
- What happens when this is compiled? java class P { P(int x) { } P() { } } class C extends P { } // in main: C c = new C(5);
- What happens when C is compiled? java class P { static void s() { } } class C extends P { @Override static void s() { } }
- Which lazily-initialised singleton is thread-safe WITHOUT any explicit synchronization or volatile field?
- What is printed? java // static generic method of the main class: static <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b)…
- What is printed? java class A { private int v = 1; boolean same(A other) { return v == other.v; } void set(A other) { other.v = 9; } } //…