0
String s1 = "testing";
String s2 = new String("testing");

System.out.println((s1.toString() == s2.toString()) ? "True":"False");

System.out.println(("another" == "another") ? "True":"False");

Output:

False

True

I know we should not use == to compare strings in Java because it will compare the references to these objects, not the strings itself and hence outputs would be unexpected. But if we compare both strings it should output true. Why is this happening? On the other hand, you can see that the second statement outputs true as excepted.

user8114666
  • 125
  • 1
  • 9
  • 2
    The link has all the answers – Scary Wombat Aug 01 '17 at 01:16
  • @ScaryWombat I understand that == will output false when both objects have different references but their toString() methods return the same string then why it still outputs false. – user8114666 Aug 01 '17 at 01:23
  • 1
    @user8114666 Because `toString()` doesn't intern - the references are still different. `System.out.println(("testing".intern() == new String("testing").intern()) ? "True" : "False");` and the answer to your question is the `String` intern pool. – Elliott Frisch Aug 01 '17 at 01:25
  • 1
    "but their toString() methods return the same string" `toString` method of String class returns `this`. So `s1.toString() == s2.toString()` is same as `s1 == s2` and since both references hold different objects (one from string pool, other created explicitly via `new`) `==` returns false. – Pshemo Aug 01 '17 at 01:31

0 Answers0