ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
class Box<T> {
T value;
}
// in main:
Box<String> b1 = new Box<>();
Box<Integer> b2 = new Box<>();
System.out.println(b1.getClass().equals(b2.getClass()));- A. false
- B. true
- C. Compilation error
- D. Depends on insertion order
Correct answer: B. true
T is erased to Object in the compiled Box class, so there is only one Box.class at run time regardless of how many type arguments are used at compile time. Both b1 and b2 share that single Class object, so the comparison is true.
More OOP with C++ and Java questions
- What is printed (assume typical compiler codegen)? cpp struct Base { ~Base() { cout << "~Base "; } }; struct Derived : Base { int buf =…
- What happens when this line is compiled? java List<String>[] arr = new List<String>[10];
- What is printed? java class A { static void who() { System.out.print("A"); } } class B extends A { static void who() {…
- What is printed? java class K { int a, b; K(int a, int b) { this.a = a; this.b = b; } public int hashCode() { return 1; } public boolean…
- What is printed? java class Counter { private int count = 0; void inc() { count++; } int get() { return count; } } class LoggingCounter…
- What is printed? java String a = "hel" + "lo"; String b = "hello"; System.out.println(a == b);