Java · Question 14 · Hard

What will be the output of the following Java program?

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Set<String> s = new HashSet<>();
        s.add("a");
        s.add("A");
        s.add("a");
        s.add(new String("a"));
        System.out.println(s.size());
    }
}
  1. 3
  2. 4
  3. 1
  4. 2
Answer and explanation

Answer: D. 2

Explanation: HashSet uses equals() and hashCode(), so new String("a") is a duplicate of "a". Strings are case-sensitive, so "a" and "A" are different. The set holds {"a", "A"}.

Previous: What will be the output of the following Java program (default JVM settings)? · Next: What will be the output of the following Java program?

Practise java

Try a fresh set of java questions with an explanation after every answer, free and without signing up: Java practice. Or sit a full placement mock test.

More java questions

More technical & programming practice

Python · Data Structures · Algorithms · Object-Oriented Programming · DBMS · SQL · Operating Systems · Computer Networks

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge