ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> m = new HashMap<>();
m.put(new String("key"), 1);
m.put("key", 2);
System.out.println(m.size() + " " + m.get("key"));
}
}- A. 2 1
- B. 1 2
- C. 2 2
- D. 1 1
Correct answer: B. 1 2
String correctly overrides both equals() and hashCode() based on content, so new String("key") and the literal "key" are treated as the same key by HashMap despite being different objects. The second put() overwrites the first entry's value, leaving size 1 and the stored value 2.
More OOP with C++ and Java questions
- What is printed? java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder("abc"); try {…
- What is printed? java class A { A() { System.out.print("A "); } } class B extends A { B() { System.out.print("B "); } B(int x) { this()…
- What happens when this is compiled? java class A { A(int x) { System.out.print("A(int) "); } } class B extends A { B() {…
- What is printed? cpp struct A { A() { cout << "A"; } ~A() { cout << "~A"; } }; struct B { A a; B() { cout << "B"; } ~B() { cout << "~B"; }…
- What is printed? java class Base { protected int val; Base(int v) { val = v; System.out.print("Base(" + val + ") "); } } class Derived…
- What is printed? cpp struct Logger { Logger(string tag) : tag(tag) { cout << "open-" << tag << " "; } ~Logger() { cout << "close-" << tag…