String comparison and String interning in Java

You should almost always use equals. You can be certain that string1 == string2 will work if:

  • You’ve already made sure you’ve got distinct values in some other way (e.g. you’re using string values fetched from a set, but comparing them for some other reason)
  • You know you’re dealing with compile-time string constants
  • You’ve manually interned the strings yourself

It really doesn’t happen very often, in my experience.

Leave a Comment