0

When we do:

String a = new String("abc");
String b = new String ("abc");

and do a a == b it returns false because they are 2 diferent objects.
But when we have this:

String c = "abc";
String d = "abc";

and we do a c == d it returns true. Why is that? Should it return false also? Why does the == operator behaves as a .equals() method in this case?

alexandre1985
  • 1,056
  • 3
  • 13
  • 31

1 Answers1

1

This happens because Java uses a so called Stringpool and tries to reuse old String-Literals to save some memory. But if you say "new String" you always create a new Object based on the Literal. See: here I would suggest you to always use the Objects.equals(a, b) if you want to make sure the objects are equal (or call equal on the Object itself if you're sure it's not null)

Community
  • 1
  • 1
Mariano
  • 478
  • 4
  • 9