-5

String a = "test";

why is "test".equals(a) true?

does the "test" in "test".equals(a) get the same reference as a from the string pool? Thanks

  • The second question you ask is unrelated to the actual question (or the other way around). `equals` *should* make a logically meaningful comparison, and therefore it does make sense that `"test"` is equal to `a` because they have the same value, String pooling and string comparison are actually irrelevant here. You are mixing two completely unrelated topics. – luk2302 Jan 26 '21 at 12:37
  • 3
    Why wouldn't it be true? – f1sh Jan 26 '21 at 12:40

1 Answers1

1

equals for String does not do a reference compare, does a value one.

For other classes you create, if you dont override equals and hashcode, it will do a reference compare, otherwise it will call your override.

Ali Ben Zarrouk
  • 1,891
  • 16
  • 24