LearnFrenzy
Sign in Take a free test

Object Class and Wrapper Classes · Predict the Output · Question 14

A broken, non-symmetric equals Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 14 Back to Exercise

What is the output of the following Java program?

Main.java
class CaseInsensitive {
    final String s;
    CaseInsensitive(String s) { this.s = s; }

    @Override public boolean equals(Object o) {
        if (o instanceof CaseInsensitive c) return s.equalsIgnoreCase(c.s);
        if (o instanceof String str) return s.equalsIgnoreCase(str);      // tries to equal Strings too
        return false;
    }
    @Override public int hashCode() { return s.toLowerCase().hashCode(); }
}

public class Main {
    public static void main(String[] args) {
        CaseInsensitive ci = new CaseInsensitive("Java");
        String str = "java";
        System.out.println(ci.equals(str) + " " + str.equals(ci) + " " + ci.equals(new CaseInsensitive("JAVA")));
    }
}
  • A true false true Correct
  • B true true true
  • C false false true
  • D true false false
Correct Answer: Option A

String.equals knows nothing about CaseInsensitive, so symmetry is broken – a classic example of why equals should only accept its own type.

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