Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison and String interning in Java

When should one compare Strings as objects and when should one use their equals method? To make sure, I always use equals, but that doesn't seem very efficient. In what situations can I be certain that string1 == string2 is a safe to use?

Thanks!

like image 555
Albus Dumbledore Avatar asked Oct 07 '10 20:10

Albus Dumbledore


2 Answers

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.

like image 122
Jon Skeet Avatar answered Sep 23 '22 13:09

Jon Skeet


From what I know of Java, string1==string2 will only be true if the references to those objects are the same. Take a look at the following case

String string1 = new String("Bob");
String string2 = new String("Bob");

string1 == string2; // false, they are seperate objects
string1 = string2;  // asigning string1 to string2 object
string1 == string2; // true, they both refer to the same object
like image 26
Anthony Avatar answered Sep 23 '22 13:09

Anthony