ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
String a = "Aa", b = "BB";
Set<String> set = new HashSet<>();
set.add(a); set.add(b);
System.out.print((a.hashCode() == b.hashCode()) + " " + a.equals(b) + " " + set.size());
  1. A. false false 2
  2. B. true false 1
  3. C. true true 1
  4. D. true false 2

Correct answer: D. true false 2

String.hashCode is s[0]·31 + s[1]: 65·31 + 97 = 2112 and 66·31 + 66 = 2112, a collision. A HashSet then checks equals, which is false, so both strings are kept.

More OOP with C++ and Java questions

Exams that ask this topic