LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 16

Equality based on private fields Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 16 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

final class Email {
    private final String value;
    Email(String v) { value = v.strip().toLowerCase(); }
    @Override public boolean equals(Object o) { return o instanceof Email e && value.equals(e.value); }
    @Override public int hashCode() { return Objects.hash(value); }
    @Override public String toString() { return value; }
}

public class Main {
    public static void main(String[] args) {
        Set<Email> set = new HashSet<>();
        set.add(new Email("Asha@Mail.com"));
        set.add(new Email(" asha@mail.com "));
        set.add(new Email("ravi@mail.com"));
        System.out.println(set.size() + " " + set.contains(new Email("ASHA@MAIL.COM")));
    }
}
  • A 2 true Correct
  • B 3 false
  • C 3 true
  • D 2 false
Correct Answer: Option A

The constructor normalises the address, so equal emails are always stored the same way and compare equal.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links